0

特定の単語がテキストで使用されている回数を数えようとしていますString text。新しいメソッドを作成する必要がありますか

public int countWords(....) {

}

または、Javaには準備ができていますか?ありがとう

4

5 に答える 5

2

StringUtils.countMatches次のように使用します。

int count = StringUtils.countMatches("abcdea","a");

ここに参照があります

お役に立てれば!

編集:

その場合、正規表現を使用して問題を解決できます。Matcherクラスを使用します。

Pattern myPattern = Pattern.compile("YOUR_REGEX_HERE");
Matcher myMatcher = myPattern.matcher("YOUR_TEXT_HERE");

int count = 0;
while (myMatcher.find())
    count ++;
于 2013-09-24T21:51:46.167 に答える
2

純粋なJavaを使用したソリューションは次のとおりです。

public static int countOccurences(String text, String word) {
  int occurences = 0;
  int lastIndex = text.indexOf(word);
  while (lastIndex != -1) {
    occurences++;
    lastIndex = text.indexOf(word, lastIndex + word.length());
  }
  return occurences;
}
于 2013-09-24T21:56:19.277 に答える
1

これが私の解決策です:

Pattern myPattern = Pattern.compile("word");
Matcher myMatcher = myPattern.matcher("word");

int count = 0;
while (myMatcher.find()){
    count ++;
}
于 2013-09-25T03:02:14.920 に答える