統計字符串每個字符出現的次數
阿新 • • 發佈:2018-07-26
new java util value 集合 append oid import gen
1 package cn.yschung.demo; 2 3 import java.util.Arrays; 4 import java.util.HashMap; 5 import java.util.Set; 6 7 public class StirngDemo { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 String ch = "aababcabcdabcddasae"; 12 //轉成數組 13 char[] arr = ch.toCharArray(); 14 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); 15 16 for (char s : arr) { 17 // 得到鍵值 18 Integer c = hm.get(s); 19 if (c == null) {// 如果c=空,則集合的值就為1 20 hm.put(s, 1);21 } else { 22 c++; 23 hm.put(s, c); 24 } 25 } 26 27 Set<Character> set = hm.keySet(); 28 // 遍歷集合 29 for (Character i : set) { 30 Integer ss = hm.get(i);// 獲取value值 31 StringBuilder sb = newStringBuilder();// 創建StringBuilder 32 sb.append(i).append("(").append(ss).append(")"); 33 String result = sb.toString(); 34 System.out.println(result); 35 } 36 37 } 38 39 }
統計字符串每個字符出現的次數