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

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

Description

count Matches

License

Apache License

Declaration

public static int countMatches(String str, String sub) 

Method Source Code

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

public class Main {
    public static final int INDEX_NOT_FOUND = -1;

    public static int countMatches(String str, String sub) {
        if (!hasText(str) || !hasText(sub)) {
            return 0;
        }/*from  w  w  w . java  2  s  .  c om*/
        int count = 0;
        int idx = 0;
        while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
            count++;
            idx += sub.length();
        }
        return count;
    }

    public static boolean hasText(String str) {
        return str != null && !str.trim().isEmpty();
    }

    /**
     * Removes the leading and trailing occurence of the string trim.
     * <p/>
     * trim("||||FOO|BAR|||||","|") => FOO|BAR
     *
     * @param str
     * @param trim
     * @return
     */
    public static String trim(String str, String trim) {
        str = trimLeading(str, trim);
        str = trimTrailing(str, trim);
        return str;
    }

    /**
     * Removes the leading occurence of the string trim.
     * <p/>
     * trim("||||FOO|BAR|||||","|") => FOO|BAR|||||
     *
     * @param str
     * @param trim
     * @return
     */
    public static String trimLeading(String str, String trim) {
        while (str.startsWith(trim)) {
            str = str.substring(trim.length());
        }
        return str;
    }

    /**
     * Removes the trailing occurence of the string trim.
     * <p/>
     * trim("||||FOO|BAR|||||","|") => ||||FOO|BAR
     *
     * @param str
     * @param trim
     * @return
     */
    public static String trimTrailing(String str, String trim) {
        while (str.endsWith(trim)) {
            str = str.substring(0, str.length() - trim.length());
        }
        return str;
    }
}

Related

  1. countMatches(String s, String sb)
  2. countMatches(String str, String match)
  3. countMatches(String str, String sub)
  4. countMatches(String str, String sub)
  5. countMatches(String str, String sub)
  6. countMatches(String str, String sub)
  7. countMatches(String str, String sub)
  8. countMatches(String str, String sub)
  9. countMatches(String string, char find)