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 int countMatches(String str, String sub) {
        if ((isEmpty(str)) || (isEmpty(sub))) {
            return 0;
        }/*  w w w. j  a  v  a2  s. c om*/
        int count = 0;
        int idx = 0;
        while ((idx = str.indexOf(sub, idx)) != -1) {
            count++;
            idx += sub.length();
        }
        return count;
    }

    public static boolean isEmpty(String str) {
        return (str == null) || (str.length() == 0);
    }

    public static int indexOf(String str, char searchChar) {
        if (isEmpty(str)) {
            return -1;
        }
        return str.indexOf(searchChar);
    }

    public static int indexOf(String str, char searchChar, int startPos) {
        if (isEmpty(str)) {
            return -1;
        }
        return str.indexOf(searchChar, startPos);
    }

    public static int indexOf(String str, String searchStr) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }
        return str.indexOf(searchStr);
    }

    public static int indexOf(String str, String searchStr, int startPos) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }
        if ((searchStr.length() == 0) && (startPos >= str.length())) {
            return str.length();
        }
        return str.indexOf(searchStr, startPos);
    }
}

Related

  1. countMatches(String reference, String query)
  2. countMatches(String s, String sb)
  3. countMatches(String str, String match)
  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 str, String sub)