Write code to count Matches in a string
//package com.book2s; public class Main { public static void main(String[] argv) { String str = "book2s.com"; String subStr = "book2s.com"; System.out.println(countMatches(str, subStr)); }//from w ww . j ava2s.co m public static int countMatches(String str, String subStr) { if ((str == null) || (str.length() == 0) || (subStr == null) || (subStr.length() == 0)) { return 0; } int count = 0; int index = 0; while ((index = str.indexOf(subStr, index)) != -1) { count++; index += subStr.length(); } return count; } }