public static int getWordCount(String content){
int count = 0;
String cn_words = content.replaceAll("[^(\\u4e00-\\u9fa5,。《》?;’‘:“”【】、)(……¥!·)]", "");
int cn_words_count = cn_words.length();
String non_cn_words = content.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":><?\\[\\])]", " ");
int non_cn_words_count = 0;
String[] temp = non_cn_words.split(" ");
for(String ch:temp){
if(ch.trim().length() != 0) non_cn_words_count++;
}
count = cn_words_count + non_cn_words_count;
return count;
}
public static void main(String[] args) {
System.out.println(getWordCount("我爱你 zhanglulu _")); // 输出5,单词是以空格分开,所以这里我爱你三个字加一个单词zhanglulu和一个下划线,空格不算。
}
Java获取字符串单词个数
最新推荐文章于 2024-04-22 16:46:37 发布