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
  • 34,719
  • 24
  • 185
  • 251
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
  • 7,761
  • 3
  • 17
  • 40
Muthu
  • 188
  • 8