1、如何统计 String 中字符的个数
@Test
public void countCharacter() {
String str = "jfefuieffdjfiedfdjf";
// 使用 hashmap 存储统计
HashMap<Character, Integer> result = new HashMap<>();
for (char ch : str.toCharArray()) {
result.put(ch, result.getOrDefault(ch, 0) + 1);
}
// 遍历输出集合
for (Map.Entry entry : result.entrySet()) {
System.out.println("字符 " + entry.getKey() + " 个数 : " + entry.getValue());
}
}