zoukankan      html  css  js  c++  java
  • JavaSe 统计字符串中字符出现的次数

        public static void main(String[] args) {
            // 1、字符串
            String str = "*Constructs a new <tt>HashMap</tt> with the same mappings as the *  specified <tt>Map</tt>. The<tt>HashMap</tt> is created with default load factor (0.75) and aninitial capacity sufficient to*hold the mappings in the specified<tt>Map</tt>.";
            // 2.把字符串转换为数组
            char[] charArr = str.toCharArray();
            // 3.创建一个Map
            Map<Character, Integer> counterMap = new HashMap<Character, Integer>();
            // 4.遍历一个Map
            for (int i = 0; i < charArr.length; i++) {
                // 5.拿到的字符作为键到集合中去找值
                Integer value = counterMap.get(charArr[i]);
                if (value == null) {
                    // 把字符作为键,1为值存入集合
                    counterMap.put(charArr[i], 1);
                } else {
                    // 把值加1重新写入集合
                    value += 1;
                    counterMap.put(charArr[i], value);
                }
            }
            Set<Map.Entry<Character, Integer>> entrySet = counterMap.entrySet();
            for (Map.Entry<Character, Integer> entry : entrySet) {
                System.out.println(entry.getKey() + " 字符出现次数=" + entry.getValue());
            }
        }
  • 相关阅读:
    制造者为什么重要
    归因理论
    初创业谨记有三法宝:顶梁柱、现金牛、北极星
    华特迪士尼语录
    说好一个创业故事的5个步骤
    接口
    抽象类_模板方法设计模式
    抽象类与抽象方法
    非static和static初始化块
    单例设计模式
  • 原文地址:https://www.cnblogs.com/chenyanbin/p/13412631.html
Copyright © 2011-2022 走看看