newJavaUser newJavaUser - 1 year ago 71
Java Question

How do I count the number of unique characters in a string? - Updated

For example, the string "abc" should give 3 unique characters, while the string "abcccd" would give 4 unique characters. I'm not allowed to use Map, HashMap, TreeMap, Set, HashSet, StringBuffer or TreeSet in this.

So far I'm trying to use a for loop but when I run the program I keep getting 0 unique characters. I'm kind of new at Java so I really have no idea what I'm doing.

Edit: so I changed the code around and I'm getting a result but it ends up being 1 less than what I want. I'll type in 'abc' and the result will come up as "2 unique characters" instead of three. To counter that I put (uniqueChars + 1) in the println statement. Is this a good correction? If the user puts nothing, it will still say that there's 1 unique character.

Updated code:

userText = userText.toLowerCase(); // userText is declared earlier in the program
// as the user's input. Setting this to lowercase
// so it doesn't say "a" and "A" are two different
// characters.
int uniqueChars = 0;
for (int i = 0; i < lengthText-1; i++) { // lengthText is declared earlier
// as userText.length();
if (userText.charAt(i) != userText.charAt(i+1))
System.out.println("there are " + (uniqueChars + 1) + " unique characters in your string.");

Answer Source

This is what I came up with:

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();
    char characters[] = lowerCase.toCharArray();
    int countOfUniqueChars = s.length();
    for (int i = 0; i < characters.length; i++) {
        if (i != lowerCase.indexOf(characters[i])) {
    return countOfUniqueChars;

I just check the index for every character, and if it's different from the original index, there are multiple occurrences.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download