如何查找字符串中的不同字符个数 [英] How to find number of distinct characters in a string

查看:31
本文介绍了如何查找字符串中的不同字符个数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须计算字符串中不同字母表中不同字符的数量,因此在本例中计数将为-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

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

推荐答案

使用Java 8时,这要容易得多。您可以使用类似以下内容

return string.chars().distinct().count();

这篇关于如何查找字符串中的不同字符个数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆