0

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

Buras
  • 3,069
  • 28
  • 79
  • 126

5 Answers5

2

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 ++;
LuisCien
  • 6,362
  • 4
  • 34
  • 42
2

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;
}
Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
1

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.

EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16
1
int counter = 0;
while(myString.contains("textLookingFor")){
myString.replaceFirst("textLookingFor","");
counter++;
}
Crickcoder
  • 2,135
  • 4
  • 22
  • 36
1

Here is my solution:

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

int count = 0;
while (myMatcher.find()){
    count ++;
}