统计字符串中每个字母出现的次数
package com.ibeifeng;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
/*3 "acfabfaefcbefcaefbcecdfabccdec",获取字符串中每一个字母出现的次数。
* 如:结果:a(5)b(4)c(8)d(2)e(4)f(6) (15分)*/
public class Demo3 {
public static void main(String[] args) {
String str = "acfabfaefcbefcaefbcecdfabccdec";
HashMap<Character,Integer> hm = new HashMap();
//存入
for(int i=0; i<str.length(); i++) {
char ch = str.charAt(i);
if(hm.containsKey(ch)) {
int count = hm.get(ch);
hm.put(ch, count+1);
} else {
hm.put(ch, 1);
}
}
//遍历
// Set<Character> set = hm.keySet();
// String result = "";
// for (Character key : set) {
// result=result+key+"("+hm.get(key)+")";
// }
// System.out.println(result);
//遍历
Set<Character> set = hm.keySet();
String result = "";
ArrayList<Character> arrList= new ArrayList();
arrList.addAll(set);
Collections.sort(arrList);
for (Character key : arrList) {
result=result+key+"("+hm.get(key)+")";
}
System.out.println(result);
}
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。