Here you can find the source of countMatches(final CharSequence str, final CharSequence sub)
public static int countMatches(final CharSequence str, final CharSequence sub)
//package com.java2s; //License from project: Open Source License public class Main { private static final int INDEX_NOT_FOUND = -1; public static int countMatches(final CharSequence str, final CharSequence sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; }//from w ww . j a v a 2s. c o m int count = 0; int idx = 0; while ((idx = str.toString().indexOf(sub.toString(), idx)) != INDEX_NOT_FOUND) { count++; idx += sub.length(); } return count; } public static int countMatches(final CharSequence str, final char ch) { if (isEmpty(str)) { return 0; } int count = 0; // We could also call str.toCharArray() for faster look ups but that would generate more garbage. for (int i = 0; i < str.length(); i++) { if (ch == str.charAt(i)) { count++; } } return count; } public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } }