- import java.util.*;
- public class MapTest2 {
- public static void main(String[] arg){
- String str = "aaaasdsdszA";
- System.out.println(charCount(str));
- }
-
- public static String charCount(String str){
- char[] chs = str.toCharArray();
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
- int count = 0;
- for(int i = 0;i<chs.length;i++){
- if( chs[i]>='a'&&chs[i]<='z'|| chs[i]>='A'&&chs[i]<='Z')
- if(tm.containsKey(chs[i])){
- count = tm.get(chs[i]);
- tm.put(chs[i], count+1);
- }
- else tm.put(chs[i],1);
- }
-
- StringBuilder sb = new StringBuilder();
- Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
- while(it.hasNext()){
- Map.Entry<Character,Integer> me = it.next();
- Character ch = me.getKey();
- Integer value = me.getValue();
- sb.append(ch+":"+value+" ");
- }
- return sb.toString();
- }
- }
复制代码 |