java 統計String字符串中字符的數量


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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM