0

How can I use the String.contains("string") method for all occurrences of a word in a string, not just the first occurrence of the word?

Cœur
  • 37,241
  • 25
  • 195
  • 267
D Doe
  • 33
  • 5
  • 3
    If there was a method for **counting** the occurrences of one string in another, it would **not** be called `contains` - which implies a boolean of either `true` or `false`. – Andrew Thompson Feb 18 '18 at 01:46

1 Answers1

1

String.contains only return Boolean.

If you want count the occurrence of string

String str = "java string contain return boolean. java java";
String findStr = "java";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
   count ++;
   lastIndex += findStr.length();
 }
}
System.out.println(count);
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
Muthu
  • 156
  • 8