输入字符串统计其中每个字符的个数
public class HashDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入字符串:");
String str = sc.next();
char[] chars = str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<>();
for (char aChar : chars) {
if (hm.containsKey(aChar)){ //如果字符出现过,那么value值加一
Integer integer = hm.get(aChar);
integer++;
hm.put(aChar,integer);
}else {
hm.put(aChar,1); //如果字符没有出现过,则将字符放入key值,同时设置value值为一
}
}
System.out.println(hm);
}
}
输出结果:
aaaabbbbbbccc
{a=4, b=6, c=3}
Process finished with exit code 0
本文介绍了一种使用Java编程语言统计输入字符串中每个字符出现次数的方法。通过使用HashMap数据结构,该方法能够有效地记录并输出每个字符的频率。
2192

被折叠的 条评论
为什么被折叠?



