Counting letters in a string using two for-loops

后端 未结 4 413
臣服心动
臣服心动 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.

    0 讨论(0)
  • 2021-01-17 05:23
    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);
    }
    
    0 讨论(0)
  • 2021-01-17 05:30

    On the second for loop, just go through each character of string and compare it with the current character of first for loop.

    (not the solution I would do, just following your instructors hint)

    Another way is to store values within a map with the chars as key and a counter of occurrences as value.

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

    UPDATE:

    //iterating on the map to output values:
    for (char key : map.keySet()) {
       System.out.println(key+": "+map.get(key));
    }
    
    0 讨论(0)
  • 2021-01-17 05:38

    I would use a simple array. Simply convert each letter to an index and increment the array at that index.

    int letters[26];
    int index = ch - 'a';
    letters[index]++;
    
    0 讨论(0)
提交回复
热议问题