【发布时间】:2013-03-10 02:20:24
【问题描述】:
我必须读取字符串 "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);
}
【问题讨论】:
-
对于每个字符,遍历字符串并增加计数器,如果你看到它。
-
所以你什么都没试过?
-
能否请您准确发布您的老师给您的代码。
-
不应该
ch='z'是ch<='z'? -
@ajp15243 我会这么说。另外,我个人会在 for 子句中声明
ch,而不是在它上面。