- import java.util.*;
- class Test
- {
- public static void main(String[] args)
- {
- String s =charCount("assddffaagh");
- System.out.println(s);
- }
- public static String charCount(String str)
- {
- char[] chs =str.toCharArray();
- TreeMap<Character,Integer> tm =new TreeMap<Character,Integer>();
- for(int x = 0; x <chs.length; x++);//这个for循环里面的x变量不存在?为什么
- {
- Integer value = tm.get(chs[x]);
- if(value==null)
- {
- tm.put(chs[x],1);
- }
- else
- {
- value = value +1;
- tm.put(chs[x],value);
- }
-
- }
- 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();
- }
- }
复制代码 |
|