Java String Char Count countChars(String s, boolean countDigits, boolean countLetters, boolean countOthers)

Here you can find the source of countChars(String s, boolean countDigits, boolean countLetters, boolean countOthers)

Description

count Chars

License

Creative Commons License

Declaration

public static int countChars(String s, boolean countDigits, boolean countLetters, boolean countOthers) 

Method Source Code

//package com.java2s;
/*/*w ww  . j  a  va2s  .  c om*/
 * This software is in the public domain under CC0 1.0 Universal plus a
 * Grant of Patent License.
 *
 * To the extent possible under law, the author(s) have dedicated all
 * copyright and related and neighboring rights to this software to the
 * public domain worldwide. This software is distributed without any
 * warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication
 * along with this software (see the LICENSE.md file). If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
 */

public class Main {
    public static int countChars(String s, boolean countDigits, boolean countLetters, boolean countOthers) {
        // this seems like it should be part of some standard Java API, but I haven't found it
        // (can use Pattern/Matcher, but that is even uglier and probably a lot slower)
        int count = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                if (countDigits)
                    count++;
            } else if (Character.isLetter(c)) {
                if (countLetters)
                    count++;
            } else {
                if (countOthers)
                    count++;
            }
        }
        return count;
    }

    public static int countChars(String s, char cMatch) {
        int count = 0;
        for (char c : s.toCharArray())
            if (c == cMatch)
                count++;
        return count;
    }
}

Related

  1. countChar(String text, char c)
  2. countChar(String text, char ch)
  3. countChar(StringBuffer sb, char ch)
  4. countChars(String data)
  5. countChars(String input)
  6. countChars(String s, char c)
  7. countChars(String s, char c)
  8. countChars(String s, char c)
  9. countChars(String s, String charset)