如何字符统计java
字符统计的方法
使用字符串的 length() 方法
在 Java 中,字符串的字符数可以通过调用 length() 方法获取。该方法返回字符串中 Unicode 字符的数量。

String str = "Hello, 世界";
int charCount = str.length();
System.out.println("字符数: " + charCount); // 输出: 8
处理 Unicode 代理对(特殊字符)
如果字符串包含 Unicode 代理对(如表情符号或某些特殊字符),length() 方法可能无法正确统计实际显示的字符数。可以使用 codePointCount() 方法解决。

String str = "Hello, 😊";
int codePointCount = str.codePointCount(0, str.length());
System.out.println("实际字符数: " + codePointCount); // 输出: 7
按字节统计
如果需要统计字符串的字节数(如 UTF-8 编码),可以使用 getBytes() 方法。
String str = "Hello, 世界";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
System.out.println("字节数: " + bytes.length); // 输出: 12
统计特定字符的出现次数
遍历字符串,统计某个字符的出现次数。
String str = "abracadabra";
char target = 'a';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == target) {
count++;
}
}
System.out.println("字符 'a' 出现次数: " + count); // 输出: 5






