使用Map集合统计字符串中某个字符出现的次数
源码
:
String str = "qqqwwweeeerr111我爱爱爱爱爱你";
Map<Character, Integer> map = new HashMap<>(); //定义Map集合
for (int i = 0; i < str.length(); i++) {
int count = 0; //初始化count的值
for (int j = 0; j < str.length(); j++) { // 遍历一次str字符串
if (str.charAt(i) == str.charAt(j)) {//判断字符串i下标和j下标的字符是否相等,若相等就让count自增
count++;
}
}
map.put(str.charAt(i), count); //把下标为i的字符和他的出现次数存进去
}
System.out.println(map); //输出Map集合
运行结果:
{你=1, q=3, 1=3, 我=1, 爱=5, r=2, e=4, w=3}