public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input a string:");
String _str = s.nextLine(); // 输入要统计的字符串
Map<Character, Integer> map = countChar(_str);
System.out.println(map);
}
static Map<Character, Integer> countChar(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
char c = '\0';
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (map.containsKey(Character.valueOf(c))) // 如果Map存在该k值则返回 true。
map.put(Character.valueOf(c), Integer.valueOf(map.get(
Character.valueOf(c)).intValue() + 1));
else
map.put(Character.valueOf(c), Integer.valueOf(1));
}
return map;
}
统计某字符串中每个字符出现的次数
最新推荐文章于 2023-05-06 22:28:18 发布