Java字数统计
2019-08-05 本文已影响1人
小智pikapika
多语言环境下,统计字数or单词数的方法:
1、中文按照字符个数统计
中文正则表达式为"[\u4e00-\u9fa5]"
,用该正则统计出所有的中文字符即可
2、其他语言按照标点、空格分隔统计单词数
标点符号空格正则表达式为"[\\p{P}\\p{S}\\p{Z}\\s]+"
,排除中文字符后按照该正则表达式分隔一下统计单词数即可 ( Java正则原本不需要加{}
,即"[\\pP\\pS\\pZ\\s]+"
, Android不加则会抛异常 )
最终的统计方法:
public static int wordCount(String string) {
if (string == null) {
return 0;
}
String englishString = string.replaceAll("[\u4e00-\u9fa5]", "");
String[] englishWords = englishString.split("[\\p{P}\\p{S}\\p{Z}\\s]+");
int chineseWordCount = string.length() - englishString.length();
int otherWordCount = englishWords.length;
if (englishWords.length > 0 && englishWords[0].length() < 1) {
otherWordCount--;
}
if (englishWords.length > 1 && englishWords[englishWords.length - 1].length() < 1) {
otherWordCount--;
}
return chineseWordCount + otherWordCount;
}