zoukankan      html  css  js  c++  java
  • JAVA经典题--计算一个字符串中每个字符出现的次数

    需求:  计算一个字符串中每个字符出现的次数

    思路: 

    通过toCharArray()拿到一个字符数组-->

    遍历数组,将数组元素作为key,数值1作为value存入map容器-->

    如果key重复,通过getKey()拿到value,计算value+1后存入

    代码如下:

    import java.util.*;
    
    public class MapDemo {
        
        public static void main(String[] args) {
            String str = "sdnasjhdasdaksnfcjdshdfufhaosinfdsjncxkjz";
            Map<Character,Integer> map = new HashMap<Character,Integer>();
            char[] arr = str.toCharArray();
            
            for (char ch : arr) {
                if (map.containsKey(ch)) {
                    Integer old = map.get(ch);
                    map.put(ch, old + 1);
                } else {
                    map.put(ch,1);
                }
            }
            System.out.println(map);
        }
    }
  • 相关阅读:
    二维数组111
    基础笔记
    排序
    折半查找法2
    数组 最小值
    数组 求偶数
    数组 找下标
    数组
    阶乘与9 99 999 9999 99999...
    打印三角形
  • 原文地址:https://www.cnblogs.com/Kingram/p/9048757.html
Copyright © 2011-2022 走看看