все в этом коде хорошо, но у меня возникают проблемы со второй строкой. Он возвращает 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;
}
}
}
Проверка верхнего или нижнего регистра. Преобразуйте шаблон и строку в один и тот же регистр перед подсчетом. – Jan
Проблема с чувствительностью к регистру «The». Попробуйте использовать while ((index = fullString.toLowerCase(). IndexOf (partString.toLowerCase(), index))! = -1) {" – achin