Counting occurrences of a substring or character in a string

suggest change

countMatches method from org.apache.commons.lang3.StringUtils is typically used to count occurences of a substring or character in a String:

import org.apache.commons.lang3.StringUtils;

String text = "One fish, two fish, red fish, blue fish";

// count occurrences of a substring
String stringTarget = "fish";
int stringOccurrences = StringUtils.countMatches(text, stringTarget); // 4

// count occurrences of a char
char charTarget = ',';
int charOccurrences = StringUtils.countMatches(text, charTarget); // 3

Otherwise for does the same with standard Java API’s you could use Regular Expressions:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
String text = "One fish, two fish, red fish, blue fish";
System.out.println(countStringInString("fish", text)); // prints 4
System.out.println(countStringInString(",", text)); // prints 3

public static int countStringInString(String search, String text) {
    Pattern pattern = Pattern.compile(search);
    Matcher matcher = pattern.matcher(text);
    int stringOccurrences = 0;
    while (matcher.find()) {
    return stringOccurrences;

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents