import java.util.*;
public class CharacterCount {
public static String CharCount(String str) {
char []chs = str.toCharArray();//将字符串转换为字符数组。
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
int count = 0;
for (int x = 0; x < chs.length; x++){
if (!(chs[x] >= 'a' && chs[x] <= 'z') || (chs[x] >= 'A' && chs[x] <= 'Z'))
continue;
Integer value = tm.get(chs[x]);//返回chs[x]键所对应的值Value.
if (value != null)
count = value;
count++;
tm.put(chs[x], count);
count = 0; //每次循环前计数器清零
}
Set<Map.Entry<Character, Integer>> entrySet = tm.entrySet();//返回此映射中包含的映射关系的 Set 视图。
Iterator<Map.Entry<Character, Integer>> it = entrySet.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext())
{
Map.Entry<Character, Integer> me = it.next();
Character ch = me.getKey();
Integer in = me.getValue();
sb.append(ch + ":" + in + "次\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(CharCount("abcdekkaqoq"));
}
} |