統計一個字元串中每一個字元出現的次數

  • 2020 年 1 月 23 日
  • 筆記

本文提供三種方案,本質都是先將字元串轉為數組:

  • String.charAt(index)
  • String.split("")
  • String.toCharArray()

具體如下:

    /**       * 通過String.charAt(index)獲取字元串中的字元       * @param str       */      public static void count(String str){          Map<Character, Integer> map = new HashMap<Character, Integer>();          int total = 0;          Character tmp = null;          for (int i=0;i<str.length(); i++) {              tmp = str.charAt(i);              total = 1;              if (map.containsKey(tmp)) {                  total = map.get(tmp)+1;              }              map.put(tmp, total);          }          PrintUtill.printlnRule();          PrintUtill.println(map);      }        /**       * String.charAt(index)的變種,將最後存儲的Character類型轉為String類型       * @param str       */      public static void count2(String str){          Map<String, Integer> map = new HashMap<String, Integer>();          int total = 0;          String tmp = null;            String maxChar = str.charAt(0) + "";          int maxToal = 1;            for (int i=0;i<str.length(); i++) {              tmp = str.charAt(i) + "";              total = 1;              if (map.containsKey(tmp)) {                  total = map.get(tmp)+1;              }              map.put(tmp, total);              if (maxToal<total) {                  maxToal = total;                  maxChar = tmp;              }          }          PrintUtill.printlnRule();          PrintUtill.println(map);          PrintUtill.println( "出現次數最多的字母是:" + maxChar + ",出現次數是:" + maxToal);      }        /**       * 通過String.split("")將字元串直接切割成字元串數組       * @param str       */      public static void count3(String str){          Map<String, Integer> map = new HashMap<String, Integer>();          int total = 0;          String[] myStrs = str.split("");          String tmp = null;          for (int i=0;i<myStrs.length; i++) {              tmp = myStrs[i];              total = 1;              if (map.containsKey(tmp)) {                  total = map.get(tmp)+1;              }              map.put(tmp, total);          }          PrintUtill.printlnRule();          PrintUtill.println(map);      }        /**       * 通過String.toCharArray()將字元串轉為char數組       * @param str       */      public static void count4(String str){          Map<String, Integer> map = new HashMap<String, Integer>();          int total = 0;          char[] myStrs = str.toCharArray();          String tmp = null;          for (int i=0;i<myStrs.length; i++) {              tmp = myStrs[i] + "";              total = 1;              if (map.containsKey(tmp)) {                  total = map.get(tmp)+1;              }              map.put(tmp, total);          }          PrintUtill.printlnRule();          PrintUtill.println(map);      }

相關下載

點擊下載

Tags: