在Java中,计算一个字符串中每个字符出现次数

  • Post author:
  • Post category:java




1、直接上代码
public class CheckWord {

    public static void main(String[] args) {
        /*1.定义一个字符串*/
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一串字符:");
        String word = input.next();
        showWord(word);
    }

    /**
     * 计算字符串中,字符出现的次数
     * @param word 字符串
     */
    private static void showWord(String word) {
        /*2.创建一个Map,字母作为键,次数作为值*/
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        /*3.遍历字符串,得到每个字母*/
        for (int i = 0; i < word.length(); i++) {
            /*根据索引获取字符*/
            char atr = word.charAt(i);

            /*判断是否包含这个字母*/
            if (!map.containsKey(atr)) {
                /*4.如果map中没有这个字母,次数设置为1次*/
                map.put(atr, 1);
            } else {
                /*5.如果map中有这个字母,次数+1*/
                int count = map.get(atr);
                map.put(atr, count + 1);
            }
        }

        /*6.遍历map集合*/
        Set<Map.Entry<Character, Integer>> entrySets = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entrySets) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

}


2、输出打印结
请输入一串字符:
alibababilibili
a : 3
b : 4
i : 5
l : 3



版权声明:本文为weixin_42140851原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。