Java Count Characters present in a String using Apache Commons Lang

Tags: CharSetUtils Apache Commons Apache Commons Lang String

In this Java tutorial we learn how to count the number of characters present in a given String using the CharSetUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to count number of character present in a String in Java

The Apache Commons Lang library provides the method CharSetUtils.count() to count the number of characters present in a specified String and return the result of counting. You can learn how to use the CharSetUtils.count() method via the example code below.

CountCharactersPresentInString.java

import org.apache.commons.lang3.CharSetUtils;

public class CountCharactersPresentInString {
    public static void main(String... args) {
        String stringToCount = "Simple Solution";

        int result1 = CharSetUtils.count(stringToCount, "k-n");
        int result2 = CharSetUtils.count(stringToCount, "x-z");
        int result3 = CharSetUtils.count(stringToCount, "klmn");
        int result4 = CharSetUtils.count(stringToCount, "xyz");
        int result5 = CharSetUtils.count(stringToCount, "k", "l", "m", "n");
        int result6 = CharSetUtils.count(stringToCount, "x", "y", "z");

        System.out.println("Count \"k-n\" result: " + result1);
        System.out.println("Count \"x-z\" result: " + result2);
        System.out.println("Count \"klmn\" result: " + result3);
        System.out.println("Count \"xyz\" result: " + result4);
        System.out.println("Count \"k\", \"l\", \"m\", \"n\" result: " + result5);
        System.out.println("Count \"x\", \"y\", \"z\" result: " + result6);
    }
}
The output is:
Count "k-n" result: 4
Count "x-z" result: 0
Count "klmn" result: 4
Count "xyz" result: 0
Count "k", "l", "m", "n" result: 4
Count "x", "y", "z" result: 0

Happy Coding 😊