Count Occurrences of a Character

JavaJavaBeginner
Practice Now

Introduction

In Java, we can easily count the number of times a specific character occurs in a string. This lab will guide you through different methods you can use to count the occurrences of a character in a string.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/type_casting("`Type Casting`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/scope -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/classes_objects -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/class_methods -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/modifiers -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/oop -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/packages_api -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/wrapper_classes -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/identifier -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/arrays -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/data_types -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/for_loop -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/if_else -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/operators -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/output -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/strings -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/type_casting -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/variables -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/string_methods -.-> lab-117402{{"`Count Occurrences of a Character`"}} java/system_methods -.-> lab-117402{{"`Count Occurrences of a Character`"}} end

Iterative Approach

We can use an iterative approach to traverse through each character in a string to count the number of times a specific character occurs.

Create a Java file named CountOccurrences.java in the ~/project directory, and copy the following contents to the file:

public class CountOccurrences {

    public static int countChars(String str, char c) {
        int count = 0;

        for(int i = 0; i < str.length(); i++) {
            char currChar = str.charAt(i);
            if(currChar == c)
                count += 1;
        }

        return count;
    }

    public static void main(String[] args) {
        String s = "Java is an awesome language!";
        int charCountOfA = countChars(s, 'a');
        int charCountOfG = countChars(s, 'g');
        int charCountOfE = countChars(s, 'e');

        System.out.println("The String is: " + s);
        System.out.println("Character count of 'a': " + charCountOfA);
        System.out.println("Character count of 'g': " + charCountOfG);
        System.out.println("Character count of 'e': " + charCountOfE);
    }

}

To compile and run the program, run the following commands in the terminal:

cd ~/project
javac CountOccurrences.java && java CountOccurrences

The output should be:

The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3

Recursion Approach

We can also use a recursive approach to count the occurrences of a character in a string. This involves using two methods, with the first being recursive and the second one invoking the first.

Copy and paste the following code block after Step 1 code block in the CountOccurrences.java file:

public static int countCharsRecur(String str, char c, int idx) {
    if(idx >= str.length())
        return 0;
    else {
        int count = 0;
        if(str.charAt(idx) == c)
            count = 1;
        return count + countCharsRecur(str, c, idx + 1);
    }
}

public static int countChars(String s, char c) {
    return countCharsRecur(s, c, 0);
}

To compile and run the updated program, run the same commands as in Step 1:

cd ~/project
javac CountOccurrences.java && java CountOccurrences

Using Java 8 Streams

We can use Java 8 Streams to count the occurrences of a character in a string.

Copy and paste the following code block after Step 2 code block in the CountOccurrences.java file:

public static void usingStreams(String s) {
    int charCountOfA = (int) s.chars().filter(c -> c == 'a').count();
    int charCountOfG = (int) s.chars().filter(c -> c == 'g').count();
    int charCountOfE = (int) s.chars().filter(c -> c == 'e').count();

    System.out.println("The String is: " + s);
    System.out.println("Character count of 'a': " + charCountOfA);
    System.out.println("Character count of 'g': " + charCountOfG);
    System.out.println("Character count of 'e': " + charCountOfE);
}

To use the Java 8 Streams method, add the following line of code to the main method after the Step 2 code block:

usingStreams(s);

To compile and run the updated program, run the same commands as in Step 1:

cd ~/project
javac CountOccurrences.java && java CountOccurrences

Using External Libraries

We can use external libraries to count the occurrences of a character in a string.

Using Guava Library

The Guava library provides the CharMatcher class that can count the number of occurrences of a given character.

Add the following code block after the Step 3 code block:

public static int usingGuava(String str) {
    CharMatcher cm = CharMatcher.is('a');
    int charCountOfA = cm.countIn(str);

    System.out.println("Character count of 'a': " + charCountOfA);
    return charCountOfA;
}

To use the Guava library, add the following imports to the top of the CountOccurrences.java file:

import com.google.common.base.CharMatcher;

In the main method, call the usingGuava method with the string parameter:

usingGuava(s);

To compile and run the updated program, run the same commands as in Step 1:

cd ~/project
javac -cp ".:./lib/*" CountOccurrences.java && java -cp ".:./lib/*" CountOccurrences
Using Apache Library

The Apache Commons library provides a StringUtils class that has a convenient countMatches() method that takes a char and a string as input and returns the count of the character in that String as output.

Add the following code block after the Step 4 code block:

public static int usingApache(String str) {
    int charCountOfA = StringUtils.countMatches(str, 'a');
    int charCountOfG = StringUtils.countMatches(str, 'g');
    int charCountOfE = StringUtils.countMatches(str, 'e');

    System.out.println("Character count of 'a': " + charCountOfA);
    System.out.println("Character count of 'g': " + charCountOfG);
    System.out.println("Character count of 'e': " + charCountOfE);

    return charCountOfA;
}

To use the Apache Commons library, add the following import to the top of the CountOccurrences.java file:

import org.apache.commons.lang3.StringUtils;

In the main method, call the usingApache method with the string parameter:

usingApache(s);

To compile and run the updated program, run the same commands as in Step 1, with an added classpath:

cd ~/project
javac -cp ".:./lib/*" CountOccurrences.java && java -cp ".:./lib/*" CountOccurrences

Summary

In this lab, we covered the following steps:

  1. Iterative Approach - traverse through each character to count occurrences of a character.
  2. Recursive Approach - use recursion to count occurrences of a character.
  3. Java 8 Streams - use Streams to count occurrences of a character.
  4. External Libraries - use Guava and Apache libraries to count occurrences of a character.

After completing this lab, you should have a better understanding of different methods to count occurrences of a character in a string.

Other Java Tutorials you may like