想起String中沒有這種統計的方法,之前有看到過這個問題,有點興趣,寫一下思路:
定義一個String
然后把String 轉成char數組
定義一個hashmap
然后遍歷出char數組的數據,然后在hashmap里找對應的key,如果沒有,put進map,如果有,在原來值上+1
最后再遍歷輸出就可以了。思路很簡單
// 定義一個String String str="aaabbccccdddddddj"; // 定義一個map HashMap<Character, Integer> map=new HashMap(); // 字符串轉換成數組 char[] chars=str.toCharArray(); // 定義一個數字 int num=1; // for循環判斷 for(char a:chars){ // 如果map里沒有,那么就put進去 if(!map.containsKey(a)){ map.put(a,1); }else{ map.put(a,map.get(a)+1); } } for(char c:map.keySet()){ System.out.println("key:"+c+"====value:"+map.get(c)); }