找到"将"在一个句子里

时间:2017-01-28 20:25:00

标签: java string

大家好,我是新手,所以请原谅我,如果我太天真了。

我刚刚开始使用Java,所以我不是在寻找答案,但如果你能指出我的方向,那就太好了!

我只是想找到" will"在一个句子里。

这是下面的代码:

String input =
          "You have brains in your head "
        + "You have feet in your shoes "
        + "You can steer yourself "
        + "Any direction you choose "
        + "You're on your own And "
        + "you know what you know "
        + "And YOU are the guy who’ll "
        + "decide where to go "
        + "You’ll get mixed up "
        + "of course, as you already know "
        + "You’ll get mixed up with "
        + "many strange birds as you go "
        + "So be sure when you step "
        + "Step with care and great "
        + "tact and remember that "
        + "Life’s A Great Balancing Act "
        + "And will you succeed "
        + "Yes You will indeed "
        + "ninety eight and three quarter percent guaranteed "
        + "KID YOU’LL MOVE MOUNTAINS ";

这是我迄今为止所做的。但我一直得到答案1但应该是2。

public Integer occurrencesOfWord(String word)

          {

              int wordCount = 0;


              if(input.indexOf(word) >=0)
              {
                 wordCount++; 
              }

                 return wordCount;
          }




System.out.println("Occurences of word 'will': " + mainClass.occurrencesOfWord("will"));

1 个答案:

答案 0 :(得分:1)

在方法'occurrencesOfWord'中尝试以下内容。

int i = 0;
Pattern p = Pattern.compile(word);
Matcher m = p.matcher( input );
while (m.find()) {
    i++;
}

return i;