Java Char Count countCharacter(final String sourceString, final char lookFor)

Here you can find the source of countCharacter(final String sourceString, final char lookFor)

Description

count Character

License

Open Source License

Parameter

Parameter Description
sourceString a parameter
lookFor a parameter

Return

Returns the number of characters which are found in the string or -1 when the string is null

Declaration

public static int countCharacter(final String sourceString, final char lookFor) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (C) 2005, 2016 Wolfgang Schramm and Contributors
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation version 2 of the License./*from w  w  w. j av a 2s.  c o  m*/
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *******************************************************************************/

public class Main {
    /**
     * @param sourceString
     * @param lookFor
     * @return Returns the number of characters which are found in the string or -1 when the string
     *         is <code>null</code>
     */
    public static int countCharacter(final String sourceString, final char lookFor) {

        if (sourceString == null) {
            return -1;
        }

        int count = 0;

        for (int i = 0; i < sourceString.length(); i++) {
            final char c = sourceString.charAt(i);
            if (c == lookFor) {
                count++;
            }
        }

        return count;
    }
}

Related

  1. countChar(final int[] locator, final char c)
  2. countChar(final String aString, final char aChar)
  3. countChar(final String host, final char charactor)
  4. countChar(int start_index, int end_index, StringBuffer txt, char c)
  5. countChar(String a_text, char a_character)
  6. countCharacter(String content, char character)
  7. countCharacterOccurrences(String string, char c)
  8. countCharacters(String code, char c, int start, int end)
  9. countCharacters(String str, char chr)