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

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

    public static void main(String[] args) {
            char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
            char[][] countArr = new char[array.length][2];
            int lastIndex = 0;
            for (char c : array) {
                int foundIndex = -1;
                for (int i = 0; i < lastIndex; i++) {
                    if (countArr[i][0] == c) {
                        foundIndex = i;
                        break;
                    }
                }
                if (foundIndex >= 0) {
                    int a = countArr[foundIndex][1];
                    countArr[foundIndex][1] = (char) ++a;
                } else {
                    countArr[lastIndex][0] = c;
                    countArr[lastIndex][1] = '1';
                    lastIndex++;
                }
            }
            for (int i = 0; i < lastIndex; i++) {
                System.out.println(countArr[i][0] + " " + countArr[i][1]);
            }
        }
    

提交回复
热议问题