我必须读取字符串“hello world”并仅使用 for 循环输出每个字母的频率。讲师暗示我需要使用两个循环,并为我们提供了以下代码来开始:
int ch, count;
for (ch ='a'; ch <='z'; ch++) {
//count the number of occurrences in a line
//Print the count>0
}
编辑:我想我应该解决这个问题并发布我一年前找到的解决方案,因为这个问题已经得到了相当多的点击。
int count;
int value;
for (int i=65; i<91; i++) {
count=0;
for (int j=0; j<S.length; j++) {
value=(int)S[j];
if (value == i) {
count++;
}
}
if (count>0)
System.out.println((char)i+" -- "+count);
}
最佳答案
在第二个 for 循环中,只需遍历字符串的每个字符并将其与第一个 for 循环的当前字符进行比较。
(不是我会做的解决方案,只是按照你的老师的提示)
另一种方法是在映射中存储值,其中字符作为键,出现次数计数器作为值。
HashMap<Character,Integer> map = new HashMap<>();
for (int ii=0; ii<string.length; ii++) {
char c = string.charAt(ii);
if (map.containsKey(c)) {
map.put(c, get(c)++);
} else {
map.put(c, 1);
}
}
更新:
//iterating on the map to output values:
for (char key : map.keySet()) {
System.out.println(key+": "+map.get(key));
}
关于java - 使用两个 for 循环计算字符串中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532866/