Counting unique characters in a String given by the user

Here another solution:

public static int countUniqueCharacters(String input) {
    String buffer = "";
    for (int i = 0; i < input.length(); i++) {
        if (!buffer.contains(String.valueOf(input.charAt(i)))) {
            buffer += input.charAt(i);
        }
    }
    return buffer.length();
}

The first occurance of each character is stored in buffer. Therefore you have of all characters one in buffer, therefore buffer.length() delivers the count you need.


It is extremely easy :)

public static int countUniqueCharacters(String input) {
    boolean[] isItThere = new boolean[Character.MAX_VALUE];
    for (int i = 0; i < input.length(); i++) {
        isItThere[input.charAt(i)] = true;
    }

    int count = 0;
    for (int i = 0; i < isItThere.length; i++) {
        if (isItThere[i] == true){
            count++;
        }
    }

    return count;
}

Example for input "aab"

First for-cycle goes 3 times, each time for one char.

Value of "a" is 97, so it turns isItThere[97] to true, then second "a" is involved, which is doing the same, isItThere[97] is set to true again (hence changing nothing).

After that "b" is involved, value of char "b" is 98, therefore isItThere[98] is set to true.

And then you have second for-cycle, where you cycle through the all isItThere array. If you find any true statement, you increment count. In our case, you find isItThere[97] and isItThere[98] as true statement, it means you increment twice and returning 2.


If your stuck on Java 7, you can use an ArrayList and just add unique values to it, then return the size of the ArrayList, which should always work even if the count is zero.

 import java.util.ArrayList;

 public int getUniqeCount( String arg )
 {
     ArrayList<Character> unique = new ArrayList<Character>();
     for( int i = 0; i < arg.length(); i++)
         if( !unique.contains( arg.charAt( i ) ) )
             unique.add( arg.charAt( i ) );
     return unique.size();
 }

Using Java 8 you could do the following:

public static long countUniqueCharacters(String input) {
    return input.chars()
            .distinct()
            .count();
}

This creates an IntStream of chars, then takes only distincts values and then counts the number of occurences.

Tags:

Java