首页 > 代码库 > 华为上机练习题--统计各小写字符出现的次数
华为上机练习题--统计各小写字符出现的次数
题目:
手动输入一个字符串,仅限小写字母,统计并输出每个字符在字符串中出现的次数,并输出。提示可以用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;
}
}