统计字符串中每个字符出现的次数(Java实现)

要求:键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。

思路:

①键盘录入一个字符串

②创建HashMap集合(或者TreeMap集合)键是Character,值是Integer

③遍历字符串,得到每一个字符

④拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值

若拿到的值为null:说明改字符在HashMap集合中不存在,就把该字符作为键,1作为值存储

若拿到的值不为null:说明改字符在HashMap集合中存在,把该值+1,然后重新存储该字符和对应的值

⑤遍历HashMap集合,得到键和值

⑥输出结果

代码:

public class demo {
    public static void main(String[] args) {

        //键盘录入一个字符串
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s=sc.nextLine();

        //创建 HashMap集合(TreeMap集合),Character为键,Integer为值
      //  HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        TreeMap<Character,Integer> hm=new TreeMap<Character,Integer>();

        //遍历字符串,得到每一个字符HashMap集合中去找对应的值

        for (int i=0;i<s.length();i++){
            char key=s.charAt(i);
            Integer value = hm.get(key);
            //拿得到的每一个字符作为键到
            if (value==null){
                hm.put(key,1);
            } else {
                value++;
                hm.put(key,value);
            }
        }

        //遍历HashMap集合
        StringBuilder sb=new StringBuilder();
        Set<Character> keyset =hm.keySet();
        for (Character key:keyset){
            Integer value = hm.get(key);
            sb.append(key).append(":").append(value).append("
");
        }
        String result= sb.toString();
        System.out.println(result);
     }
}

运行结果:

经验分享 程序员 微信小程序 职场和发展