I am trying to count the number of times a certain word is used in a piece of text, which is String text
. Do I have to create a new method
public int countWords(....) {
}
Or is there any ready thing in Java? Thanks
I am trying to count the number of times a certain word is used in a piece of text, which is String text
. Do I have to create a new method
public int countWords(....) {
}
Or is there any ready thing in Java? Thanks
Use StringUtils.countMatches
like so:
int count = StringUtils.countMatches("abcdea","a");
Here is the reference
Hope this helps!
Edit:
Well, in that case you could use Regex to solve your problem. Use the Matcher
class:
Pattern myPattern = Pattern.compile("YOUR_REGEX_HERE");
Matcher myMatcher = myPattern.matcher("YOUR_TEXT_HERE");
int count = 0;
while (myMatcher.find())
count ++;
Here's a solution using pure 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;
}
This may be over complicating it, but,
We could use a StringTokenizer
to tokenize the String text
based on spaces as your delimiter.
You'd use the nextToken()
method to grab each word and compare it with your search term.
int counter = 0;
while(myString.contains("textLookingFor")){
myString.replaceFirst("textLookingFor","");
counter++;
}
Here is my solution:
Pattern myPattern = Pattern.compile("word");
Matcher myMatcher = myPattern.matcher("word");
int count = 0;
while (myMatcher.find()){
count ++;
}