主题:
手动输入一个字符串,只有小写字母,统计每个字符和输出频率中出现的串,输出。提示可以使用map
样例:输入:aaabbbccc
输出:a 3
b 3
c 3
分析: 看到后面的提示,简直就是不用动脑,直接简单粗暴的顺势而上
直接上代码:
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TestCharAcount {
public static void main(String args[]) {
String strIn = "aaabbbccc";
TestCharAcount tc = new TestCharAcount();
Map<Character, Integer> mTemp = tc.charAcount(strIn);
Set<Character> ks = mTemp.keySet();//生成索引set
for(Iterator<Character> it=ks.iterator(); it.hasNext(); ){//遍历索引取值
char c = it.next();
System.out.println(c + " " + mTemp.get(c));
}
}
public Map<Character, Integer> charAcount(String strIn) {
String tempStr = strIn;
// The map is sorted according to the natural ordering of its keys
//treemap是以键的自然顺序来存储值的
Map<Character, Integer> m = new TreeMap<Character, Integer>();
char[] strC = tempStr.toCharArray();
for (int i = 0; i < strC.length; i++) {
Integer count = m.get(strC[i]);
if (null == count)
count = 0;
count++;
m.put(strC[i], count);
}
return m;
}
}