/**
* 计算一个字符串中每个字符出现的次数
*/
public static Map<Character, Integer> countChart(String strings) {
//map集合存储统计结果 <字符不能重复,统计个数可以重复>
Map<Character, Integer> map = new HashMap<>();
//转换为字符串数组
char[] chars = strings.toCharArray();
//遍历字符串,获取每个字符
for (char c : chars) {
//使用获取到的字符,去map集合中判断key是否存在
if (map.containsKey(c)) {//key存在
Integer value = map.get(c);//通过key获取value(字符个数)
value++;//本身加1
map.put(c, value);
} else {//key不存在,就是第一次存储
map.put(c, 1);
}
}
return map;
}
public static void main(String[] args) {
Map<Character, Integer> map = countChart("chinese");
System.out.println(map);
}
java[算法]计算一个字符串中每个字符出现的次数
于 2021-10-31 19:13:51 首次发布