Search code examples
javastringletters

Counting the number of unique letters in a string


I have to write code that counts how many unique letters are in a string: e.g

"aabbcdefff"

This will return 6 as there are 6 different letters in the string. Currently I have the code:

  String letters = ("aabbcdefff");              
  char temp = ' ';
   for (int i = 0; i < letters.length(); i++){
      temp = inp.charAt(i);
      if (temp != ' ') {   //doesnt count spaces as letters
        alphabetSize = alphabetSize+1;
          for (int j = 0; j < inp.length(); j++){
            tempInp = tempInp.replace(temp,' ');
        }
      }
    }   

The idea of this code is that it should when detecting a letter, replace all instances of it with a space. When i run this code however, it just gives me the length of the string. What am i doing wrong? Is there another more elegant way to do this?

Thanks for your help.


Solution

  • You are fine by just using a Set.

    Loop over your string, and add each letter to your set. afterwards, check length of your set, and your done.