取出一个字符串中字母出现的次数。如:字符串:”abcdekka27qoq”,输出格式为:a(2)b(1)k(2)…
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class 获取字母出现的次数 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char[] ch = s.toCharArray();
Map<Character,Integer> map = new TreeMap();
for (int i = 0; i < ch.length; i++) {
char key = ch[i];
int value = 1;
if (map.get(key) != null) {
value = value + map.get(key);
}
map.put(key,value);
}
//映射关系的类型是Map.Entry类型,它是Map接口的内部接口
Set mappings = map.entrySet();
for (Object mapping :mappings) {
Map.Entry entry = (Map.Entry) mapping;
System.out.print(entry.getKey() + "{" + entry.getValue() + "}" + " ");
}
}
}