import java.util.Map;
import java.util.TreeMap;
/*
* 练习:
* "fdgavcbsacdfs" 获取该字符串中,每一个字母出现的次数。
* 要求打印结果是:a(2)b(1)...;
* */
class 每个字符出现次数并排序_TreeMap练习 {
public static void main(String[] args) {
String str = "fdgavcbsacdfs";
System.out.println(characterNumber(str).replace(",", ")").replace("=", "("));//打印字母出现次数
}
//打印字母出现次数
private static String characterNumber(String str) {
char[] ch = str.toCharArray();
Map<Character, Integer> tm = new TreeMap<>();
for (int i = 0; i < ch.length; i++) {
Integer value = tm.get(ch[i]);
/*if (value == null) {
tm.put(ch[i],1);
} else {
tm.put(ch[i], value+1);
}*/
tm.put(ch[i], value == null ? 1 : value+1);
}
System.out.println(tm.toString());//{a=2, b=1, c=2, d=2, f=2, g=1, s=2, v=1}
str = tm.toString().replace("=", "(").replace(",", ")");
System.out.println(str);//{a(2) b(1) c(2) d(2) f(2) g(1) s(2) v(1}
str = str.substring(1, str.length()-1) + ")";//a(2) b(1) c(2) d(2) f(2) g(1) s(2) v(1)
return str;
}
}
01-15
225
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)