Search code examples
javacharacteruniquecounting

Counting unique characters in a string


So i have been trying to make a code that counts the number of words in a string which was pretty easy. I'm running into problems when im trying to make it count the number of unique characters in a string. The program compiles and runs it doesn't display the number of Unique characters. Adding a System.out.println(countOfUniqueChars); below return doesn't work.

Here's the code:

public class Uniquechar{
public static void main(String[] args) {

    String s = "Jag vet inte vad jag heter idag";
    String[] parts = s.split(" ");
    int wordcount = parts.length;
    System.out.println("The number of words is" + wordcount);

    countUniqueCharacters(s);
}

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])) {
            countOfUniqueChars--;
        }
    }
    return countOfUniqueChars;
}

Solution

  • You can do System.out.println(countUniqueCharacters(s)); in the main method, to output the return value of your method. After a return, you cannot add more code. I did it for you and the output is 12, so it seems to be that there is also something wrong with your algorithm.

        int uniqeCharsCount = countUniqueCharacters(s);
        System.out.println("The number of uniqe chars is " + uniqeCharsCount);
    

    Output: 12

    Your algorithm:

    Actually you are checking every char, if this char is one more time in the string before. But you should also check if the char is anywhere in the string after the current index. You can fix it if you change your if condition to if (i != lowerCase.indexOf(characters[i]) || i != lowerCase.lastIndexOf(characters[i]))

    Output of the fixed version: 3 (n, h, r)