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);
    }
}

猜你喜欢

转载自www.cnblogs.com/Kingram/p/9048757.html