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;
/**/*from w ww  . j a  va  2s .  c  om*/
 *  Copyright (c) 2015-2016 Angelo ZERR.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *  Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
 */

public class Main {
    /**
     * Represents a failed index search.
     */
    public static final int INDEX_NOT_FOUND = -1;
    private static final int NOT_FOUND = -1;

    public static int countMatches(final CharSequence str, final CharSequence sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }
        int count = 0;
        int idx = 0;
        while ((idx = indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
            count++;
            idx += sub.length();
        }
        return count;
    }

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

    static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
        return cs.toString().indexOf(searchChar.toString(), start);
    }

    static int indexOf(final CharSequence cs, final int searchChar, int start) {
        if (cs instanceof String) {
            return ((String) cs).indexOf(searchChar, start);
        }
        final int sz = cs.length();
        if (start < 0) {
            start = 0;
        }
        for (int i = start; i < sz; i++) {
            if (cs.charAt(i) == searchChar) {
                return i;
            }
        }
        return NOT_FOUND;
    }
}

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)
  8. countMatches(String reference, String query)
  9. countMatches(String s, String sb)