【问题标题】:Counting letters in a string using two for-loops使用两个 for 循环计算字符串中的字母
【发布时间】: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&lt;='z'
  • @ajp15243 我会这么说。另外,我个人会在 for 子句中声明 ch,而不是在它上面。

标签: java string loops


【解决方案1】:

在第二个 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));
}

【讨论】:

  • 是的,很好的提示。不要忘记在每个字符后重置计数。
  • 这会有点过分。例如字母“l”会出现两次。你需要一个moe循环之前,为了消除重复,在外部使用消除重复的字符串,在内部使用完整的字符串。
  • 我将如何输出?
  • 我的代码中有一个错误:hashmap 上的键和值必须是对象。查看您的答案的编辑。
【解决方案2】:

我会使用一个简单的数组。只需将每个字母转换为索引并在该索引处递增数组。

int letters[26];
int index = ch - 'a';
letters[index]++;

【讨论】:

  • 是的,但是当读取给定的索引值时,我如何交织一个递增 1(从 0 开始)的计数器?这是我很困惑的部分。
  • 其他字符呢,比如'!'、'+'、'>'?
  • @Tdorno letters[index]++; 是计数器。
【解决方案3】:

以 sdasdadas 的评论和 Jean 各自的回答为基础:

外层 for 循环将循环遍历字母表中的每个字符,保持一个计数(每次执行外层循环时都需要重置它。)内层循环循环遍历“hello world”字符串,如果找到用作外部 for 循环的当前参数的字符。

更新 我无法在 Andre 的回答下方发表评论,但我可以提供一些伪代码来解决我认为您在关于计数器的评论中的意思。

int i;
for (ch characterOuter : alphabet){ //for each character in the alphabet
    i = 0 //i starts at zero, and returns to zero for each iteration  <-----THIS
    for (ch characterInner : "hello world"){
        if (characterOuter == characterInner){
            i++; //increase i by 1 <-----AND THIS
        }//end if
    }//end  innerfor
    if (i > 0) {
        print(characterOuter + " -- " + i);
    } //end if;   <---------------- this if statement was missing
}//end outer for

另外,请参阅this question

【讨论】:

  • 我喜欢 Ben 的方法,但它会重复每个字符而不是显示一次
  • 你的意思是你的执行陷入了一个无限循环,还是你的意思是它打印了每个字符的每个实例?
  • 哦,我明白了。你只需要另一个 if 语句。我会调整代码。
【解决方案4】:
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);
}

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多