Find duplicate characters in a String and count the number of occurances using Java

前端 未结 30 2473
遇见更好的自我
遇见更好的自我 2020-12-14 11:47

How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 12:43

    You can also achieve it by iterating over your String and using a switch to check each individual character, adding a counter whenever it finds a match. Ah, maybe some code will make it clearer:

    Main Application:

    public static void main(String[] args) {
    
            String test = "The quick brown fox jumped over the lazy dog.";
    
            int countA = 0, countO = 0, countSpace = 0, countDot = 0;
    
            for (int i = 0; i < test.length(); i++) {
                switch (test.charAt(i)) {
                    case 'a':
                    case 'A': countA++; break;
                    case 'o':
                    case 'O': countO++; break;
                    case ' ': countSpace++; break;
                    case '.': countDot++; break;
                }
            }
    
            System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot);
    
        }
    

    Output:

    A: 1
    O: 4
    Space: 8
    Dot: 1
    

提交回复
热议问题