Java - Write code to Counts how many times the substring appears in the larger string.

Requirements

Write code to Counts how many times the substring appears in the larger string.

countMatches(null, *)       = 0
countMatches("", *)         = 0
countMatches("abba", null)  = 0
countMatches("abba", "")    = 0
countMatches("abba", "a")   = 2
countMatches("abba", "ab")  = 1
countMatches("abba", "xxx") = 0
   

Demo

public class Main {
  public static void main(String[] argv) {
    String str = "book2s.com";
    String sub = "book2s.com";
    System.out.println(countMatches(str, sub));
  }//from   ww  w .  j ava  2s. com

  /**
   * <p>
   * Counts how many times the substring appears in the larger string.
   * </p>
   * 
   * <p>
   * A {@code null} or empty ("") String input returns {@code 0}.
   * </p>
   * 
   * <pre>
   * countMatches(null, *)       = 0
   * countMatches("", *)         = 0
   * countMatches("abba", null)  = 0
   * countMatches("abba", "")    = 0
   * countMatches("abba", "a")   = 2
   * countMatches("abba", "ab")  = 1
   * countMatches("abba", "xxx") = 0
   * </pre>
   * 
   * @param str
   *          the CharSequence to check, may be null
   * @param sub
   *          the substring to count, may be null
   * @return the number of occurrences, 0 if either CharSequence is {@code null}
   */
  public static int countMatches(CharSequence str, CharSequence sub) {
    if ((str == null || str.length() == 0) || (sub == null || sub.length() == 0)) {
      return 0;
    }
    int count = 0;
    int idx = 0;
    while ((idx = indexOf(str, sub, idx)) != -1) {
      count++;
      idx += sub.length();
    }
    return count;
  }

  public static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
    return cs.toString().indexOf(searchChar.toString(), start);
  }
}

Related Example