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());
        }
    }
复制代码

 

posted @   陈彦斌  阅读(460)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-07-31 ASP.Net MVC 路由及路由调试工具RouteDebug
2019-07-31 ASP.Net MVC过滤器
2019-07-31 Oracle 去重后排序
点击右上角即可分享
微信分享提示
主题色彩