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

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

    If your string only contains alphabets then you can use some thing like this.

    public class StringExample {
    public static void main(String[] args) {
        String str = "abcdabghplhhnfl".toLowerCase();
        // create a integer array for 26 alphabets.
        // where index 0,1,2.. will be the container for frequency of a,b,c...
        Integer[] ar = new Integer[26];
        // fill the integer array with character frequency.
        for(int i=0;i1) {
                char c = (char) (97+i);
                System.out.println("'"+c+"' comes "+ar[i]+" times.");
            }
        }
    }
    }
    

    Output:

     'a' comes 2 times.
     'b' comes 2 times.
     'h' comes 3 times.
     'l' comes 2 times.
    

提交回复
热议问题