- //package com.Map;
- import java.util.*;
- /*
- 练习:
- "sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。
- 希望打印结果:a(1)c(2).....
- */
- public class MapTest3
- {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String s = charCount("sdfgzxcvasdfxcvdf");
- 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++){
- 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();
- //System.out.println(tm);
-
- //return null;
- }
- }
- //打印结果{a=1, c=2, d=3, f=3, g=1, s=2, v=2, x=2, z=1}
复制代码 改好
|