Here you can find the source of countMatches(String str, String sub)
Counts how many times the substring appears in the larger String.
A null
or empty ("") String input returns 0
.
StringUtils.countMatches(null, *) = 0 StringUtils.countMatches("", *) = 0 StringUtils.countMatches("abba", null) = 0 StringUtils.countMatches("abba", "") = 0 StringUtils.countMatches("abba", "a") = 2 StringUtils.countMatches("abba", "ab") = 1 StringUtils.countMatches("abba", "xxx") = 0
Parameter | Description |
---|---|
str | the String to check, may be null |
sub | the substring to count, may be null |
null
public static int countMatches(String str, String sub)
//package com.java2s; public class Main { /**//from ww w . j a v a2 s . c o m * <p>Counts how many times the substring appears in the larger String.</p> * <p/> * <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p> * <p/> * <pre> * StringUtils.countMatches(null, *) = 0 * StringUtils.countMatches("", *) = 0 * StringUtils.countMatches("abba", null) = 0 * StringUtils.countMatches("abba", "") = 0 * StringUtils.countMatches("abba", "a") = 2 * StringUtils.countMatches("abba", "ab") = 1 * StringUtils.countMatches("abba", "xxx") = 0 * </pre> * * @param str the String to check, may be null * @param sub the substring to count, may be null * @return the number of occurrences, 0 if either String is <code>null</code> */ 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; } /** * checks for null and zero length * * @param s the string * @return true if null or zero length */ public static boolean isEmpty(final String s) { return s == null || s.length() == 0; } }