Java String Match Count countMatches(String str, String sub)

Here you can find the source of countMatches(String str, String sub)

Description

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 

License

Open Source License

Parameter

Parameter Description
str the String to check, may be null
sub the substring to count, may be null

Return

the number of occurrences, 0 if either String is null

Declaration

public static int countMatches(String str, String sub) 

Method Source Code

//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;
    }
}

Related

  1. countMatches(String str, String sub)
  2. countMatches(String str, String sub)
  3. countMatches(String str, String sub)
  4. countMatches(String str, String sub)
  5. countMatches(String str, String sub)
  6. countMatches(String string, char find)
  7. countMatches(String string, char toMatch)
  8. countMatches(String string, String other)
  9. countMatches(String theString, String... sep)