Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 621
user3628651 Avatar asked Dec 19 '25 14:12

user3628651


1 Answers

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.

like image 62
PKlumpp Avatar answered Dec 21 '25 04:12

PKlumpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!