public class Demo1 {
public static void main(String[] args){
String str = "asgsadgfasdgfasdf6565465";
String char_count = getCharCount(str);
System.out.println(char_count);
}
public static String getCharCount(String str) {
char[] chs = str.toCharArray(); //将字符串转成字符数组
Map<Character,Integer> map = new TreeMap<Character,Integer>(); //定义map集合
for (int i = 0; i < chs.length; i++) { //遍历字符数组,获取每一个字母
if(!(chs[i] >= 'a' && chs[i] <= 'z')){ //过滤掉非字母字符
if(!(chs[i] >= 'A' && chs[i] <= 'Z')){
continue;
}
}
Integer value = map.get(chs[i]); //将遍历到的字母作为键去查表,获取值
int count = 0; //用于记录次数
if(value != null){ //判断次数是否存在
count = value; //存在,就用count记录次数
}
count++; //次数不存在,就不记录,只对count自增变成1
map.put(chs[i], count); //将字符和次数进行存储
}
return toString(map);
}
public static String toString(Map<Character, Integer> map) {
StringBuilder sb = new StringBuilder(); //使用缓冲区
Set<Character> keySet = map.keySet(); //将map集合转变成set集合
for (Iterator<Character> it = keySet.iterator(); it.hasNext();) { //通过迭代器,取出map集合中的元素
Character key = it.next();
Integer value = map.get(key);
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
|
|