Java Get Number Of Occurences of String

This method returns the number of occurences of the search keyword in the entire string. Method takes two parameters, the string to be searched and the second one is the string to search for.


public static int getCountIndexOf(String string, String search) {
  String str = string;
  String ch = search;
  int count = 0 ;
  int pos = -1 ;
  while ((pos = str.indexOf(ch, pos + 1)) > -1) count++ ;

  return count;
}

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.