Counting letters in a string using two for-loops

后端 未结 4 452
臣服心动
臣服心动 2021-01-17 04:45

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 ga

4条回答
  •  情深已故
    2021-01-17 05:23

    To build off of sdasdadas's comment and Jean's respective answer:

    The outer for loop would rotate through each character in the alphabet, maintaining a count (which needs to be reset each time the outer loop executes.) The inner loop cycles through the "hello world" string, incrementing the counter if the character serving as the current argument of the outer for loop is found.

    UPDATE I can't comment below Andre's answer, but I can provide some pseudocode to address what I think you meant in your comment regarding the counter.

    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
    

    Also, see this question.

提交回复
热议问题