//"shfwsfvsnwnsnie"获取该字符串中的字母出现的次数
这是毕老师的题 我自己写了一遍,就是打印不出来 帮忙看看吧,还有就是最后为什么要toString ? 直接sb不可以吗?
public class MapTest3 {
public static void main(String[] args) {
String s=fun("shfwsfvsnwnsnie");
System.out.println(s);
}
public static String fun(String s){
char[] ch=s.toCharArray();
TreeMap<Character,Integer> tree= new TreeMap<Character,Integer>();
for(int x=0;x<ch.length;x++){
if(ch[x]>='a'&&ch[x]<='z' || ch[x]>='A'&&ch[x]<='Z')
continue;
Integer value=tree.get(ch[x]);
if(value==null){
tree.put(ch[x], 1);
}else{
value=value+1;
tree.put(ch[x], value);
}}
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character, Integer>> entry= tree.entrySet();
Iterator<Map.Entry<Character, Integer>> it=entry.iterator();
while(it.hasNext()){
Map.Entry<Character, Integer> me=it.next();
Character key=me.getKey();
Integer value1=me.getValue();
sb.append(key+"("+value1+")");
}
return sb.toString();
}}
|