Thorang Katchen Bhattarai Thorang Katchen Bhattarai - 6 months ago 24
Java Question

How to find number of distinct characters in a string

Given the following

String
:

String input;
input = "223d323dk2388s";
count(input);


My Code :

public int count(String string) {
int count=0;
String character = string;
ArrayList<Character> distinct= new ArrayList<>();
for(int i=0;i<character.length();i++){
char temp = character.charAt(i);
int j=0;
for( j=0;j<distinct.size();j++){

if(temp!=distinct.get(j)){

break;
}

}

if(!(j==distinct.size())){
distinct.add(temp);

}
}

return distinct.size();
}


Output :

I have to count the number of distinct characters alphabet in the string, so in this case the count will be - 3 (
d
,
k
and
s
).

Are there any native libraries which return me the number of characters present in that string ?

Answer

One way is to maintain an array and then maintain it's existence and get the total. This checks for all characters including special characters numbers.

boolean []chars = new boolean[256];

String s = "223d323dk2388s";
for(int i = 0; i < s.length(); ++i)
 chars[s.charAt(i)] = true;

int count = 0;
for(int i = 0; i < chars.length; ++i)
 if(chars[i]) count++;

System.out.println(count);

If you want to calculate the count of only the character, not including numbers and special symbols. Note that Captial and Small alphabets are different.

boolean []chars = new boolean[56];
String s = "223d323dk2388szZ";
for(int i = 0; i < s.length(); ++i)
{
    char ch = s.charAt(i);
    if( ch >=65 && ch <= 90)
        chars[ch - 'A'] = true;
    else if(ch >= 97 && ch <= 122)
        chars[ch - 'a' + 26] = true;//If you don't want to differentiate capital and small differently, don't add 26
}
int count = 0;
for(int i = 0; i < chars.length; ++i)
    if(chars[i]) count++;
System.out.println(count);

Other way of doing it is using a Set.

String s="223d323dk2388s";
Set<Character> set =new HashSet<Character>();
for(int i = 0; i < s.length(); ++i){
    set.add(s.charAt(i));
}
System.out.println(set.size());

If you don't want numbers and special symbols.

String s="223d323dk2388s";
Set<Character> set =new HashSet<Character>();
for(int i = 0; i < s.length(); ++i){
    char ch = s.charAt(i);
    if((ch >= 65 && ch <= 90) || (ch >=97 && ch <= 122))
        set.add(s.charAt(i));
}
System.out.println(set.size());