Close

Java - How to find substring occurrences in a String?

[Last Updated: May 19, 2018]

Java String Manipulation Java 

Following code shows how to find frequency of a substring in a given string.

public class SubstringOccurrence {
  public static int getOccurrenceOfSubstring(final String input, String substring) {
      if (input == null || substring == null || substring.length()==0) {
          return 0;
      }
      Matcher matcher = Pattern.compile(Pattern.quote(substring))
                               .matcher(input);
      int count = 0;
      for (; matcher.find(); count++)
          ;
      return count;
  }

  public static void main(String[] args) {
      String input = "Is yours and yours and yours...";
      int c = getOccurrenceOfSubstring(input, "yours");
      System.out.println(c);
      c = getOccurrenceOfSubstring(input, "and");
      System.out.println(c);
      c = getOccurrenceOfSubstring(input, "s");
      System.out.println(c);
      c = getOccurrenceOfSubstring(input, " ");
      System.out.println(c);
      c = getOccurrenceOfSubstring(input,"");
      System.out.println(c);
      c = getOccurrenceOfSubstring(input,".");
      System.out.println(c);
  }
}
3
2
4
5
0
3

See Also