/*
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。
希望打印结果:a(1)c(2).....
*/
import java.util.*;
class MapDemo3
{
public static void main(String[] args)
{
String str = "ab++cdab**cd";
str = getCount(str);
System.out.println(str);
}
public static String getCount(String str)
{
char[] ch = str.toCharArray();
TreeMap<Character, Integer> tm = 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 = tm.get(ch[x]);
if (value == null)
{
tm.put(ch[x],1);
}
else
{
value++;
tm.put(ch[x],value);
}
}
StringBuffer sb = new StringBuffer();
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 c = me.getKey();
Integer i = me.getValue();
sb.append(c+"("+i+")");
}
return sb.toString();
}
}
|
|