java - 使用两个 for 循环计算字符串中的字母

标签 java string loops

我必须读取字符串“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/

相关文章:

java - 扫描仪 NoSuchElementException

c++ - 循环遍历 Char 数组 - 拆分成单独的字符串 - Arduino

c++ - 在 C++ 中从字符串中删除数字并保留下划线

C# 计数元音

sql - 如何在列中找到连续的零?

java - 我的 Java swing 按钮不起作用

java - 在 glassfish 中安装 awstats

c++ - 获取字符串的最后一行

python - 如何在 Python 中循环列表

java - 从按钮调用java类