统计一个字符串中字符出现的次数
public static void main(String[] args) {
String str = "aaabbccm";
char [] arr = str.toCharArray();
HashMap<Character,Integer> hm = new HashMap<>();
for (char c : arr) {
if(!hm.containsKey(c)){
hm.put(c, 1);
}else{
hm.put(c, hm.get(c)+1);
}
}
System.out.println(hm);
}
public static void main(String[] args) {
String str = "Afafafafafaa我爱中国我爱千锋";
char[] array = str.toCharArray();
TreeMap<Character, Integer> map = new TreeMap<>();
for (char c : array) {
Integer num = map.get(c);
if (num == null) {
map.put(c, 1);
}else {
map.put(c, num+1);
}
}
Set<Entry<Character,Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
Character key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"("+value+")");
}
}