Java String Match Count countMatches(final CharSequence str, final char ch)

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

Description

Counts how many times the char appears in the given string.

License

Apache License

Parameter

Parameter Description
str the CharSequence to check, may be null
ch the char to count

Return

the number of occurrences, 0 if the CharSequence is null

Declaration

public static int countMatches(final CharSequence str, final char ch) 

Method Source Code

//package com.java2s;
/*/*from w ww.j a  v  a2  s  .c om*/
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

public class Main {
    /**
     * <p>
     * Counts how many times the char appears in the given string.
     * </p>
     *
     * <p>
     * A {@code null} or empty ("") String input returns {@code 0}.
     * </p>
     *
     * <pre>
     * StringUtils.countMatches(null, *)       = 0
     * StringUtils.countMatches("", *)         = 0
     * StringUtils.countMatches("abba", 0)  = 0
     * StringUtils.countMatches("abba", 'a')   = 2
     * StringUtils.countMatches("abba", 'b')  = 2
     * StringUtils.countMatches("abba", 'x') = 0
     * </pre>
     *
     * @param str
     *            the CharSequence to check, may be null
     * @param ch
     *            the char to count
     * @return the number of occurrences, 0 if the CharSequence is {@code null}
     * @since 3.4
     */
    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;
    }

    /**
     * Check whether the given String is empty.
     */
    public static boolean isEmpty(Object str) {
        return str == null || "".equals(str);
    }
}

Related

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