Counting letters in a string using two for-loops

后端 未结 4 422
臣服心动
臣服心动 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: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 map = new HashMap<>();
    
    for (int ii=0; ii

    UPDATE:

    //iterating on the map to output values:
    for (char key : map.keySet()) {
       System.out.println(key+": "+map.get(key));
    }
    

提交回复
热议问题