Search code examples
javacharacterunique

How to count unique characters (only letters and numbers)


// I have a program where I am supposed to count unique characters, only letters and numbers and don't count repeating numbers or letters. However, I have a problem finding out a way for the program not to count spaces and symbols such as "!" "@" "#" "$". So If i type in Hello! I only want the program to say "4", but it says "5" because it counts the exclamation point. Here is my code so far:

public static int countUniqueCharacters(String text1) {
        int count = 0;
        for (int i = 0; i < text1.length(); i++) {
            if (text1.substring(0, i).contains(text1.charAt(i) + ""))
                System.out.println();
            else
                count++;
        }
        return count;

    }

Solution

  • In your else block add a condition that the count will be incremented only if the given character is a letter or a digit.

    if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
        count++;
    }
    

    In your example:

    public static int countUniqueCharacters(String text1) {
        int count = 0;
        for (int i = 0; i < text1.length(); i++) {
            if (text1.substring(0, i).contains(text1.charAt(i) + "")) {
                System.out.println();
            } else if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
                count++;
            }
        }
        return count;
    }