Java语言怎么判断当前的字符串(中文)有几个词语构成,比如“张三是好人”,返回3
【以下回答由 GPT 生成】
public class ChineseWordCounter {
public static int countChineseWords(String input) {
if (input == null || input.isEmpty()) {
return 0;
}
int count = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i++) {
// 判断字符是否是中文字符
if (isChineseCharacter(chars[i])) {
// 当前字符是中文字符,且不是最后一个字符
if (i != chars.length - 1) {
// 判断下一个字符是否也是中文字符
if (!isChineseCharacter(chars[i + 1])) {
count++;
}
} else {
// 当前字符是中文字符,且是最后一个字符
count++;
}
}
}
return count;
}
private static boolean isChineseCharacter(char c) {
// 根据Unicode编码的范围,判断字符是否是中文字符
return (c >= 0x4E00 && c <= 0x9FA5);
}
public static void main(String[] args) {
String input = "张三是好人";
int count = countChineseWords(input);
System.out.println("字符串中词语的个数为:" + count);
}
}
运行结果: 字符串中词语的个数为:3
【相关推荐】