Here you can find the source of countMatches(final CharSequence str, final CharSequence sub)
Parameter | Description |
---|---|
str | the CharSequence to check, may be null |
sub | the substring to count, may be null |
public static int countMatches(final CharSequence str, final CharSequence sub)
//package com.java2s; /*/*from w ww .jav a 2 s . c om*/ * Copyright (c) 2006 Stephan D. Cote' - All rights reserved. * * This program and the accompanying materials are made available under the * terms of the MIT License which accompanies this distribution, and is * available at http://creativecommons.org/licenses/MIT/ * * Contributors: * Stephan D. Cote * - Initial concept and implementation */ public class Main { /** * Counts how many times the substring appears in the larger string. * * @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(final CharSequence str, final CharSequence sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = indexOf(str, sub, idx)) != -1) { count++; idx += sub.length(); } return count; } /** * Checks if a string is null or empty (""). * * @param str the String to check, may be null * * @return <code>true</code> if the String is empty or null, false otherwise * * @see #isNotEmpty(String) */ public static boolean isEmpty(String str) { if (str == null || str.length() == 0) { return true; } return false; } /** * @param array */ private static boolean isEmpty(final char[] array) { return (array == null) || (array.length == 0); } /** * Checks if a CharSequence is empty ("") or null. * * @param cs the CharSequence to check, may be null * * @return {@code true} if the CharSequence is empty or null */ public static boolean isEmpty(final CharSequence cs) { return (cs == null) || (cs.length() == 0); } /** * Used by the indexOf(CharSequence methods) as a green implementation of indexOf. * * @param cs the {@code CharSequence} to be processed * @param searchChar the {@code CharSequence} to be searched for * @param start the start index * * @return the index where the search sequence was found */ private static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) { return cs.toString().indexOf(searchChar.toString(), start); } }