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

前端 未结 30 2538
遇见更好的自我
遇见更好的自我 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:35

    A better way would be to create a Map to store your count. That would be a Map

    You need iterate over each character of your string, and check whether its an alphabet. You can use Character#isAlphabetic method for that. If it is an alphabet, increase its count in the Map. If the character is not already in the Map then add it with a count of 1.

    NOTE: - Character.isAlphabetic method is new in Java 7. If you are using an older version, you should use Character#isLetter

        String str = "asdfasdfafk asd234asda";
        Map charMap = new HashMap();
        char[] arr = str.toCharArray();
    
        for (char value: arr) {
    
           if (Character.isAlphabetic(value)) {
               if (charMap.containsKey(value)) {
                   charMap.put(value, charMap.get(value) + 1);
    
               } else {
                   charMap.put(value, 1);
               }
           }
        }
    
        System.out.println(charMap);
    

    OUTPUT: -

    {f=3, d=4, s=4, a=6, k=1}
    

提交回复
热议问题