繁体   English   中英

计算字符串中的唯一字符

[英]Counting unique characters in a string

因此,我一直在尝试编写一个计算字符串中字数的代码,这很简单。 当我试图让它计算字符串中唯一字符的数量时,我遇到了问题。 该程序编译并运行时不会显示唯一字符数。 添加一个System.out.println(countOfUniqueChars); 以下回报无效。

这是代码:

public class Uniquechar{
public static void main(String[] args) {

    String s = "Jag vet inte vad jag heter idag";
    String[] parts = s.split(" ");
    int wordcount = parts.length;
    System.out.println("The number of words is" + wordcount);

    countUniqueCharacters(s);
}

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();
    char characters[] = lowerCase.toCharArray();
    int countOfUniqueChars = s.length();
    for (int i = 0; i < characters.length; i++) {
        if (i != lowerCase.indexOf(characters[i])) {
            countOfUniqueChars--;
        }
    }
    return countOfUniqueChars;
}

尝试这个:

s = s.replace(" ", ""); // If you don't want to count space
char[] chars = s.toCharArray();
Set<Character> uniqueChars = new HashSet<>();

for (char c : chars) {
   uniqueChars.add(c);
}

System.out.println(c.size());

只需打印方法调用,它就会打印结果。

   System.out.println(countUniqueCharacters(s));

添加一个System.out.println(countOfUniqueChars); 以下回报无效。

它不会工作。 因为return语句后的代码不可访问。 也许您可以在return之前就做。

System.out.println(countOfUniqueChars);
return countOfUniqueChars;

您可以执行System.out.println(countUniqueCharacters(s)); 在main方法中,输出方法的返回值。 返回后,您将无法添加更多代码。 我为您做了,输出为12 ,因此看来您的算法也有问题。

    int uniqeCharsCount = countUniqueCharacters(s);
    System.out.println("The number of uniqe chars is " + uniqeCharsCount);

输出:12

您的算法:

实际上,您正在检查每个字符,如果该字符在字符串before又出现了一次。 但是,您还应该检查char是否在当前索引after的字符串中的任何位置。 如果将if条件更改为if (i != lowerCase.indexOf(characters[i]) || i != lowerCase.lastIndexOf(characters[i])) ,则可以对其进行修复if (i != lowerCase.indexOf(characters[i]) || i != lowerCase.lastIndexOf(characters[i]))

固定版本的输出:3 (n,h,r)

我建议使用Set仅保留唯一性,然后计算其大小,而不是迭代:

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();
    char characters[] = lowerCase.toCharArray();
    Set<Character> uniques = new HashSet<Character>();
    for (char c: characters) {
        uniques.add(c);
    }
    return uniques.size();
}
if (i != lowerCase.indexOf(characters[i])) {
    countOfUniqueChars--;
}

错了 您的lowerCase字符串是小写字母,因此,在character [i]中,任何大写字母在小写字母中的索引都是-1(将被计算为非唯一字符)。 您可以使用indexOf(lowerCase.charAt(i))来解决此问题。

计算字符数的一种好方法是消除重复。 意识形态是获得第一个字符,然后查找下一个出现的位置,然后不进行任何替换,一旦完成,便可以计算出唯一字符。

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();

    ///Get the first char of lowerCase
    String firstChar = lowerCase.substring(0,1);
    //Take off the first char
    String subS = lowerCase.substring(1);
    ///replace all chars equals to first char
    String replacedSubS = subS.replace(firstChar, "");

    /// Now, call method again to calculate size
    /// of the substring with first char
    // replaced by blank char
    return  1+countUniqueCharacters(replacedSubS);
}

这种方法对我有用,看看。 您可以分两行执行此操作,但我认为最好在此处进行详细说明。

添加一个System.out.println(countOfUniqueChars); 以下return无效。

这是预期的行为,因为return意味着控制流将从方法返回到调用此方法的位置。 这意味着return后的代码将不会执行,因此在类似

return countOfUniqueChars;
System.out.println(countOfUniqueChars);

System.out.println(countOfUniqueChars); 将是死代码

您可以在返回值之前尝试打印值

System.out.println(countOfUniqueChars);
return countOfUniqueChars;

或简单地在主要方法中打印返回值,例如

int count = countUniqueCharacters(s);
System.out.println(count);

或使用这种单线

System.out.println(countUniqueCharacters(s));

顺便说一句,从Java 8开始,您的代码可以像

s.toLowerCase().chars().distinct().summaryStatistics().getCount()

或者如果您想跳过空格,可以添加

s.toLowerCase().replace(" ","").chars().distinct().summaryStatistics().getCount()
public static int countUniqueCharacters(String s) {
        char [] input=s.toCharArray();
        Set<Character> charset=new HashSet<>();
        for (int i = 0; i < input.length; i++) {
            charset.add(input[i]);
        }
        return charset.size();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM