1. 程式人生 > 實用技巧 >JavaSe 統計字串中字元出現的次數

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