输出字符串中每个字符的个数,并以a(2)b(3)...的形式输出。
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class fanxing {
public static void main(String args[]) {
String s = "abssdbasg";
CharCount(s);
}
public static String CharCount(String str) {
char[] chars = str.toCharArray();
TreeMap<character integer> tm = new TreeMap<character integer>();
for(int i=0;i<chars.length;i++){
Integer value=tm.get(chars[i]);
if(value==null){
tm.put(chars[i], 1);
}
else{
value=value+1;
tm.put(chars[i], value);
}
}
StringBuffer sb=new StringBuffer();
Set<Map.Entry<character integer>> set=tm.entrySet();
Iterator<Map.Entry<character integer>> it=set.iterator();
while(it.hasNext()){
Entry<character integer> entry=it.next();
sb.append(entry.getKey()+"("+entry.getValue()+") ");
}
System.out.println(sb.toString());
return sb.toString();
}
}