Count Substring Occurrences - Java Algorithm

Java examples for Algorithm:String

Description

Count Substring Occurrences

Demo Code

public class Main {
  public static void main(String[] args) {
    String inputStr = "this is a test is";
    String keyWord = "is";

    // computing ...
    int counter = 0; // count matches
    for (int i = 0; i < inputStr.length() - keyWord.length() + 1; i++) {
      String subString = inputStr.substring(i, i + keyWord.length()).toLowerCase();
      if (subString.equals(keyWord)) {
        counter++;//from   w ww .  j  a  va2  s . co m
      }
    }

    // print the results
    System.out.println(counter);
  }
}

Related Tutorials