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

erl*_*man -5 java string character distinct

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

鉴于以下情况String

String input;
input = "223d323dk2388s";
count(input);
Run Code Online (Sandbox Code Playgroud)

我的代码:

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();
    }
Run Code Online (Sandbox Code Playgroud)

输出:3

是否有任何本地库可以返回该字符串中存在的字符数?

小智 6

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

return string.chars().distinct().count();
Run Code Online (Sandbox Code Playgroud)