1.
//从字符串中获取每个字符出现的次数 private static String getCharCount(String str) { //1. 将字符串转换成字符数组 char[] chars = str.toCharArray(); //2. Map<Character, Integer> map = new TreeMap<Character, Integer>(); for (int i = 0; i < chars.length; i++){ if (!(chars[i] >= 'a'&& chars[i] <='z' || chars[i] >= 'A'&& chars[i] <='Z')){//如果不是字母则继续遍历 continue; } //将数组中的字母作为key去查map表 Integer value = map.get(chars[i]); int count = 1; if (value != null){ count = value + 1; } map.put(chars[i],count); } return mapToString(map); } private static String mapToString(Map<Character, Integer> map) { StringBuilder sb = new StringBuilder(); Iterator<Character> it = map.keySet().iterator(); while (it.hasNext()){ Character key = it.next(); Integer value = map.get(key); sb.append(key+"("+value+")"); } return sb.toString(); }