java 统计中文字符个数能用length吗

发布时间:2023年12月18日

在Java中,统计中文字符的个数可以使用length()方法。但是,这只能统计中文字符串的长度,不能判断其中是否包含中文字符。如果你需要统计一个字符串中中文字符的个数,你可能需要使用正则表达式或者其它方式来判断每个字符是否为中文字符。

下面是一个简单的例子,这个例子中的代码可以统计一个字符串中中文字符的个数:

public class Main { ?
? ? public static void main(String[] args) { ?
? ? ? ? String str = "Hello, 你好世界!"; ?
? ? ? ? int length = str.length(); ?
? ? ? ? int chineseCharacterCount = 0; ?
??
? ? ? ? for (int i = 0; i < length; i++) { ?
? ? ? ? ? ? char c = str.charAt(i); ?
? ? ? ? ? ? if (Character.toString(c).matches("[\\u4e00-\\u9fa5]+")) { ?
? ? ? ? ? ? ? ? chineseCharacterCount++; ?
? ? ? ? ? ? } ?
? ? ? ? } ?
??
? ? ? ? System.out.println("字符串长度: " + length); ?
? ? ? ? System.out.println("中文字符个数: " + chineseCharacterCount); ?
? ? } ?
}

这段代码首先获取字符串str的长度,然后遍历字符串中的每个字符。如果字符是中文字符(通过正则表达式[\\u4e00-\\u9fa5]+判断),就增加中文字符计数器chineseCharacterCount。最后,打印出字符串的长度和中文字符的个数。

public class ChineseCharacterCounter { ?
? ? public static void main(String[] args) { ?
? ? ? ? String str = "你好,世界!"; ?
? ? ? ? int characterCount = 0; ?
? ? ? ? int byteCount = 0; ?
??
? ? ? ? for (int i = 0; i < str.length(); i++) { ?
? ? ? ? ? ? char c = str.charAt(i); ?
? ? ? ? ? ? if (Character.toString(c).matches("[\\u4e00-\\u9fa5]+")) { ?
? ? ? ? ? ? ? ? characterCount++; ?
? ? ? ? ? ? ? ? byteCount += Character.codePointCount(c, str.codePointStart(i), str.codePointEnd(i)); ?
? ? ? ? ? ? } ?
? ? ? ? } ?
??
? ? ? ? System.out.println("中文字符个数: " + characterCount); ?
? ? ? ? System.out.println("中文字符字节数: " + byteCount); ?
? ? } ?
}

在这个例子中,我们首先定义了一个包含中文字符的字符串?str。然后,我们遍历这个字符串中的每个字符,如果这个字符是中文字符(匹配正则表达式?[\\u4e00-\\u9fa5]+),我们就增加字符计数器?characterCount?和字节计数器?byteCount

Character.codePointCount(c, str.codePointStart(i), str.codePointEnd(i))?方法返回的是?c?字符在字符串?str?中所占的字节数。这是因为中文字符在 Unicode 中通常占用多个字节。

最后,我们打印出中文字符的个数和字节数。

文章来源:https://blog.csdn.net/zz_ll9023/article/details/135045746
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。