特定の単語がテキストで使用されている回数を数えようとしていますString text
。新しいメソッドを作成する必要がありますか
public int countWords(....) {
}
または、Javaには準備ができていますか?ありがとう
特定の単語がテキストで使用されている回数を数えようとしていますString text
。新しいメソッドを作成する必要がありますか
public int countWords(....) {
}
または、Javaには準備ができていますか?ありがとう
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 ++;
純粋な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;
}
これが私の解決策です:
Pattern myPattern = Pattern.compile("word");
Matcher myMatcher = myPattern.matcher("word");
int count = 0;
while (myMatcher.find()){
count ++;
}