如何查找字符串中不同字符的数量

How to find number of distinct characters in a string

我必须计算字符串中不同字符字母表的数量,因此在这种情况下,计数将为 - 3(dks)。

给出以下 String

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

我的代码:

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();
    }

输出:3

是否有任何本机库 return 我知道该字符串中存在的字符数?

一种方法是维护一个数组,然后将其填充并获得总数。这会检查所有字符,包括特殊字符和数字。

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);

如果您只想计算字母的数量,不包括数字和特殊符号,这里有一个备选方案。注意大写字母和小写字母是不同的。

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);

另一种方法是使用集合。

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());

如果您不想要数字和特殊符号。

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());

有了java8就容易多了。你可以使用这样的东西

return string.chars().distinct().count();
String s="InputString";
 String p="";
 char ch[]=s.toCharArray();
 for(int i=0;i<s.length();i++)
 {
     for(int j=i+1;j<s.length();j++)
     {
         if(ch[i]==ch[j])
         {
             ch[j]=' ';
         }
     }
     p=p+ch[i];
     p = p.replaceAll("\s",""); 
 }
   
    System.out.println(p.length());

对于那些来这里寻找 Kotlin 解决方案的人:

val countOfDistinctCharacters = string.toCharArray().distinct().size