取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,
输出格式为:a(2)b(1)k(2)...
public static void main(String[] args) {
HashMap<Character,Integer> hm=new HashMap<>();//利用不同步的HashMap储存每个字符
String str="assdjkfhjkxcvhufhwuiehfsd"; //一堆字符
char[]carr=str.toCharArray();
for (char c :carr) {//遍历
if(hm.get(c)==null) //如果hm的c键没有添加,那么添加
hm.put(c, 1);
else
hm.put(c,hm.get(c)+1); //如果有了 次数累加
}
Set <Map.Entry<Character,Integer>> s1=hm.entrySet();
Iterator<Map.Entry<Character, Integer>> i=s1.iterator();
while(i.hasNext()){
Map.Entry<Character,Integer> e=i.next();
System.out.print(e.getKey()+"("+e.getValue()+") ");
}
} |
|