例如:
输入:asdgswessdfa
输出:
a:2
d:2
e:1
f:1
g:1
s:3
w:1
代码如下
public static void myConuts(String str) {
//将字符串变成字符数组
char[] chs = str.toCharArray();
Map<Character, Integer> map = new TreeMap<Character, Integer>();
//循环遍历,统计出现的次数
for (char c : chs) {
if (map.get(c) == null) {
map.put(c, 1);
} else {
int count = Integer.valueOf(map.get(c));
map.put(c,++count);
}
}
//打印输出结果
Iterator<Character> it = map.keySet().iterator();
while (it.hasNext()){
Character key = it.next();
Integer values = map.get(key);
System.out.println(key+"\t"+values);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("输入任意字符:");
String s = in.nextLine();
//调用统计函数
myConuts(s);
}