Java中统计字符出现的次数
我们面试通常会遇到,有一个字符串,如何统计出每个字符出现的次数,这样的题目。下面利用map集合存储进行统计每个字符出现的频次。代码如下:public static void main(String[] args) {// 定义字符串String string = "fdafasfsfasf";// 定义map容器Map<Character, Integ..
·
我们面试通常会遇到,有一个字符串,如何统计出每个字符出现的次数,这样的题目。下面利用map集合存储进行统计每个字符出现的频次。
代码如下:
public static void main(String[] args) {
// 定义字符串
String string = "fdafasfsfasf";
// 定义map容器
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 1; i < string.length(); i++) {
char ch = string.charAt(i);
if (map.containsKey(ch)) {
int count = map.get(ch);
count = count + 1;
map.put(ch, count);
} else {
map.put(ch, 1);
}
}
// 遍历map集合
Set<Character> keySet = map.keySet();
for (Character chars : keySet) {
System.out.println("字符:"+chars + ",出现的次数为:"+map.get(chars));
}
}
运行结果:
字符:f,出现的次数为:4
字符:d,出现的次数为:1
字符:s,出现的次数为:3
字符:a,出现的次数为:3
更多推荐
已为社区贡献1条内容
所有评论(0)