What is StringUtils.countMatches in Java?

countMatches is a static method of the StringUtils class that is used to count the number of occurrences of a character or a substring in a larger string/text. Here, character or substring matching is case-sensitive in nature.

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

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

Note: For other versions of the commons-lang package, refer to the Maven Repository.

The StringUtils class can be imported as follows.

import org.apache.commons.lang3.StringUtils;

Method signature

public static int countMatches(final CharSequence str, final char ch)

Parameters

  • final CharSequence str: the larger string/text.
  • final char ch: the character to be counted.

Return value

The number of times the character is present in the larger string/text.

Overloaded method

public static int countMatches(final CharSequence str, final CharSequence sub)

Parameters

  • final CharSequence str: the larger string/text.
  • final CharSequence sub: the substring to be counted

Return value

The number of times the substring is present in the larger string/text.

Code

In the example below, we pass the text as "educative" and the character to be counted as 'e'. Since the character occurs twice, the program will print 2.

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String text = "educative";
char charToBeCounted = 'e';
System.out.println(StringUtils.countMatches(text, charToBeCounted));
}
}

In the code below, we pass a substring to be counted in the given text. When the program is run, 3 will be printed, as the substring occurs thrice in the string.

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String text = "hellohellohello";
String charToBeCounted = "llo";
System.out.println(StringUtils.countMatches(text, charToBeCounted));
}
}

Free Resources