2015-12-10 4 views
-1

все в этом коде хорошо, но у меня возникают проблемы со второй строкой. Он возвращает 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; 
     } 
    } 
} 
+0

Проверка верхнего или нижнего регистра. Преобразуйте шаблон и строку в один и тот же регистр перед подсчетом. – Jan

+1

Проблема с чувствительностью к регистру «The». Попробуйте использовать while ((index = fullString.toLowerCase(). IndexOf (partString.toLowerCase(), index))! = -1) {" – achin

ответ

1

Это может быть потому, что вы ищете «» с маленькими буквами, но первый «The» имеет капитал Т.

0

Это потому, что первая «The» в качестве «Т» в верхнем регистре , Если вы не хотите быть чувствительным к регистру, вам нужно преобразовать строку в нижний регистр:

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; 
} 
Смежные вопросы