How do I count the number of occurrences of a char in a String?

Category: java.lang, viewed: 981 time(s).

This example show you how to count the number of a character occurrences in a string. We show two ways to do it, using the String.replaceAll(String regex, String replace) method and creating a loop that check every char in the String and count the matched char.

package org.kodejava.example.lang;

public class CharCounter {
    public static void main(String[] args) {
        String text = "a,b,c,c,e,f,g,g,g,g,h";

        //
        // Use the CharCounter.countCharOccurrences() method to count.
        //
        int numberOfLetterC = CharCounter.countCharOccurrences(text, 'c');
        System.out.println("Letter c = " + numberOfLetterC);

        //
        // Other solution is to use the String.replaceAll() method. We'll
        // replace the chars other than the counted char with an empty string.
        // To get the char occurrences we count the lenght of the remaining
        // string.
        //
        int numberOfComma = text.replaceAll("[^,]", "").length();
        System.out.println("Comma    = " + numberOfComma);

        int numberOfLetterG = text.replaceAll("[^g]", "").length();
        System.out.println("Letter g = " + numberOfLetterG);
    }

    /**
     * Count number of specified char occurrences in the specified string.
     */
    public static int countCharOccurrences(String source, char target) {
        int counter = 0;

        //
        // Loop through the string and increment the counter if the
        // target character found in the string. 
        //
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) == target) {
                counter++;
            }
        }
        return counter;
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats