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

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

Description

count Matches

License

Open Source License

Declaration

public static int countMatches(final CharSequence str, final CharSequence sub) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

    public static int countMatches(final CharSequence str, final CharSequence sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }//from   w ww  .  j a v a 2s. c o m
        int count = 0;
        int idx = 0;
        while ((idx = str.toString().indexOf(sub.toString(), idx)) != INDEX_NOT_FOUND) {
            count++;
            idx += sub.length();
        }
        return count;
    }

    public static int countMatches(final CharSequence str, final char ch) {
        if (isEmpty(str)) {
            return 0;
        }
        int count = 0;
        // We could also call str.toCharArray() for faster look ups but that would generate more garbage.
        for (int i = 0; i < str.length(); i++) {
            if (ch == str.charAt(i)) {
                count++;
            }
        }
        return count;
    }

    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }
}

Related

  1. countMatches(CharSequence str, CharSequence sub)
  2. countMatches(final CharSequence seq, final char c)
  3. countMatches(final CharSequence str, final char ch)
  4. countMatches(final CharSequence str, final CharSequence sub)
  5. countMatches(final CharSequence str, final CharSequence sub)
  6. countMatches(final String str, final String sub)
  7. countMatches(String line, char chr)