Java String count substring matches

Description

Java String count substring matches

public class Main {
   public static int count(String s, String target) {
      int count = 0;
      int n = target.length();
      for (int i = 0; i <= s.length() - n; i++) {
         String piece = s.substring(i, i + n);
         if (piece.equals(target))
            count++;//from ww  w  .  ja v  a2s . c  o m
      }
      return count;
   }

   public static void main(String[] args) {
      System.out.println(count("this     and  this   and  that  and  this", "this"));
   }
}

Counts how many times the substring appears in the larger String.

A null or empty ("") String input returns <code>0</code>.

countMatches(null, *)       = 0
countMatches("", *)         = 0
countMatches("abba", null)  = 0
countMatches("abba", "")    = 0
countMatches("abba", "a")   = 2
countMatches("abba", "ab")  = 1
countMatches("abba", "xxx") = 0
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com demo2s.com";
    String sub = "demo";
    System.out.println(countMatches(str, sub));
  }/*from  w  w  w . jav a  2  s  .c o  m*/

  public static int countMatches(String str, String sub) {
    if (isEmpty(str) || isEmpty(sub)) {
      return 0;
    }
    int count = 0;
    int idx = 0;
    while ((idx = str.indexOf(sub, idx)) != -1) {
      count++;
      idx += sub.length();
    }
    return count;
  }
  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }
}



PreviousNext

Related