计算字符串中出现的单词数

时间:2015-12-10 06:02:22

标签: java string count boolean

此代码中的所有内容都很好,但我遇到了第二个字符串的问题。即使字符串中有四个“the”,它也会返回3而不是4。我需要一些帮助。谢谢!

public static void main(String[] args) 
{
    boolean allCorrect = true;

    allCorrect &= testCount("I love to walk to the park", "to", 2);
    allCorrect &= testCount("The theater is in the theater district.", "the", 4);
    allCorrect &= testCount("I am so happy I am getting this right!", " ", 8);
    allCorrect &= testCount("The quick brown fox jumped over the fence", "shoe", 0);
    allCorrect &= testCount("1 is a lonely number but it also always returns 0 when used before the % operator.", "1", 1);
    result(allCorrect, "countHowManyinString");
}

public class stringActivty {
    public static int countHowManyinString(String fullString, String partString)
    {
        int count = 0;
        int index = 0;
        while ((index = fullString.indexOf(partString, index)) != -1) {
            count++;
            index += partString.length();
        }
        return count;
    }
    public static boolean testCount(String strA, String strB, int answer)
    {
        int result = countHowManyinString(strA, strB);

        if (result == answer) {
            System.out.println("CORRECT! There are " + answer + " instances of \"" + strB + "\" in \"" + strA + "\"");
            return true;
        } else {
            System.out.println("Keep trying! There are " + answer + " instances of \"" + strB + "\" in \"" + strA + "\" but your method returned " + result);
            return false;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

可能是因为你正在寻找带有小写字母的“the”,但第一个“The”有大写字母。

答案 1 :(得分:0)

这是因为第一个“The”是一个大写的“T”。如果您不希望区分大小写,则必须将字符串转换为小写:

public static int countHowManyinString(String fullString, String     partString)
{
    fullString = fullString.toLowerCase()
    int count = 0;
    int index = 0;
    while ((index = fullString.indexOf(partString, index)) != -1) {
        count++;
        index += partString.length();
    }
    return count;
}