我必须读取字符串"hello world"并仅使用for循环输出每个字母的频率.教练暗示我需要使用两个循环并给我们以下代码开始:
int ch, count;
for (ch ='a'; ch <='z'; ch++) {
//count the number of occurrences in a line
//Print the count>0
}
Run Code Online (Sandbox Code Playgroud)
编辑:我想我会解决这个问题并发布我一年前找到的解决方案,因为这个问题已经得到了相当多的点击量.
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);
}
Run Code Online (Sandbox Code Playgroud)
在第二个for循环中,只需遍历字符串的每个字符,并将其与first 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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
//iterating on the map to output values:
for (char key : map.keySet()) {
System.out.println(key+": "+map.get(key));
}
Run Code Online (Sandbox Code Playgroud)