Arun K Abraham Arun K Abraham - 5 months ago 10
Java Question

How to get the total count of occurence of a word in a sentence

I am trying to find the total count of occurrence of word in a sentence.
I tried the following code:

String str = "This is stackoverflow and you will find great solutions here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";

String findStr = "hello World";
String[] split=findStr.split(" ");

for(int i=0;i<split.length;i++){
String indexWord=split[i];
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){

lastIndex = str.indexOf(indexWord,lastIndex);

if(lastIndex != -1){
count ++;
lastIndex += findStr.length();

System.out.println("Count for word "+indexWord+" is : "+count);

If I am passing string like "stack solution" ,the string should be split into two(space split) and need to find the no of occurrence of each string in the sentence.The count is perfect if I pass only one word.The code has to match even substrings containing the searched string.
Eg:-In the sentence "stack" apperars three times,but the count is only 2.


qxz qxz

When you increment lastIndex after a match, you mean to increment it by the length of the match (indexWord), not the length of the string of input words (findStr). Just replace the line

lastIndex += findStr.length();


lastIndex += indexWord.length();