Java String Match Count countMatches(String string, String other)

Here you can find the source of countMatches(String string, String other)

Description

Returns how many times string contains other.

License

Apache License

Parameter

Parameter Description
string the string to search
other the string that is searched

Return

the number of occurences

Declaration

public static int countMatches(String string, String other) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/* w  w w . j  av a 2  s .  c  o m*/
     * Returns how many times <code>string</code> contains
     * <code>other</code>.
     * @param string the string to search
     * @param other the string that is searched
     * @return the number of occurences
     */
    public static int countMatches(String string, String other) {
        if (null == string)
            return 0;
        if (null == other)
            return 0;
        if (0 >= string.length())
            return 0;
        if (0 >= other.length())
            return 0;
        int count = 0;
        int index = 0;
        while ((index <= string.length() - other.length()) && (-1 != (index = string.indexOf(other, index)))) {
            count++;
            index += other.length();
        }
        return count;
    }
}

Related

  1. countMatches(String str, String sub)
  2. countMatches(String str, String sub)
  3. countMatches(String str, String sub)
  4. countMatches(String string, char find)
  5. countMatches(String string, char toMatch)
  6. countMatches(String theString, String... sep)
  7. countMatches(String[] query, String[] entry)
  8. countMatchingLines(Throwable ex, Throwable cause)