Java,统计字符串中各字符出现的次数

时间:2023-02-13 21:50:03
public class TimesNum {
//求字符出现的次数
public static void main(String[] args) {
String strs = "awojgnjadkfjdaiongjrewngklmvcsd";
//定义一个map,key是字符,value是数字
Map<Character,Integer> map = new HashMap<Character,Integer>();
//把String转成字符数组
char[] b = strs.toCharArray();
//遍历数组
for(char c:b){
//把字母当key去map里面取值
Integer i = map.get(c);
//如果i为null,则说明map里没有对应Key的值,那么把这次统计记为1
if(null==i){
map.put(c, 1);
}
//否则就把这次统计加1,然后再次put进map中
else{
i++;
map.put(c, i);
}
}
//输出对应字母的出现次数
Set<Character> set = map.keySet();
for(Character ch:set){
System.out.print(ch+":"+map.get(ch)+"\t");
}

}

}

输出结果:

a:3 c:1 d:3 e:1 f:1 g:3 i:1 j:4 k:2 l:1 m:1 n:3 o:2 r:1 s:1 v:1 w:2