使用两个for循环计算字符串中的字母 [英] Counting letters in a string using two for-loops

查看:160
本文介绍了使用两个for循环计算字符串中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取字符串hello world并仅使用for循环输出每个字母的频率。教练暗示我需要使用两个循环并给我们开始以下代码:

I have to read the string "hello world" and output each letter's frequency using only for loops. The instructor hinted that I'd need to use two loops and gave us the following code to begin:

int ch, count;
for (ch ='a'; ch <='z'; ch++) {
  //count the number of occurrences in a line
  //Print the count>0
}

编辑:我认为我会犯这个问题发布我一年前发现的解决方案,因为这个问题已经得到了相当多的点击率。

I figured I'd necro this question and post the solution I found a year ago due to the fact that this question has been getting a decent amount of hits.

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);
}


推荐答案

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循环计算字符串中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆