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

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

    This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.

    import java.util.Arrays;
    
    public class DuplicateCharactersInString {
        public static void main(String[] args) {
            String string = "check duplicate charcters in string";
            string = string.toLowerCase();
            char[] charAr = string.toCharArray();
            Arrays.sort(charAr);
            for (int i = 1; i < charAr.length;) {
                int count = recursiveMethod(charAr, i, 1);
                if (count > 1) {
                    System.out.println("'" + charAr[i] + "' comes " + count + " times");
                    i = i + count;
                } else
                    i++;
            }
        }
    
        public static int recursiveMethod(char[] charAr, int i, int count) {
            if (ifEquals(charAr[i - 1], charAr[i])) {
                count = count + recursiveMethod(charAr, ++i, count);
            }
            return count;
        }
    
        public static boolean ifEquals(char a, char b) {
            return a == b;
        }
    }
    

    Output :

    ' ' comes 4 times
    'a' comes 2 times
    'c' comes 5 times
    'e' comes 3 times
    'h' comes 2 times
    'i' comes 3 times
    'n' comes 2 times
    'r' comes 3 times
    's' comes 2 times
    't' comes 3 times
    

提交回复
热议问题