天天看点

Java实现统计字符串中每个字符个数

今天带领大家学习

字符串中的每个字符个数的

统计方法

分析:

  1. 首先,使用Scanner获取用户输入的一个字符串;
  2. 接着,遍历字符串,获取每一个字符,String类的方法toCharArray,把每个字符串转换为一个字符数组,遍历数组;
  3. 然后使用Map集合中的方法判断获取的字符是否存储在Map集合中:使用Map集合中的方法containsKey(获取到的字符),返回的是boolean值,若为true,则字符存在,value值加一并保存,若为false,则字符不存在,将字符作为key,value赋值为1保存到Map集合中去;
  4. 最后,遍历Map集合,输出最终结果。

实现:

public class Bianli {
    public static void main(String[] args) {
        // 使用Scanner获取用户输入的字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str = sc.next();

        // 穿件Map集合,key是字符串中的字符,value是字符的个数
        HashMap<Character , Integer> map = new HashMap<>();

        // 遍历字符串,获取每一个字符
        for(char c : str.toCharArray()){
            if(map.containsKey(c)){
                // key存在
                Integer value = map.get(c);
                value++;
                map.put(c,value);
            }else{
                // key不存在
                map.put(c,1);
            }
        }

        // 遍历Map集合,输出结果
        for(Character key : map.keySet()){
            Integer value = map.get(key);
            System.out.println(key + "=" +value);
        }

    }
}
           

结果展示:

Java实现统计字符串中每个字符个数
Java实现统计字符串中每个字符个数

        感谢您的阅读,不足之处欢迎指正!