当前位置: 移动技术网 > IT编程>开发语言>Java > Java输入字符串统计其中每个字符的个数

Java输入字符串统计其中每个字符的个数

2020年08月10日  | 移动技术网IT编程  | 我要评论
输入字符串统计其中每个字符的个数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(); HashM

输入字符串统计其中每个字符的个数

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 

本文地址:https://blog.csdn.net/fengzheng_00/article/details/107872907

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网