How do I count the occurrences of a String in another String?
Author: Deron Eriksson
Description: This Java example shows how to count the number of occurrences of a String in another String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The countMatches() method of the StringUtils class of the Commons LangS library can be used to count the number of occurrences of a String in another String. The comparison is case-sensitive, so if you need it to be case-insensitive, you can make sure that both of your comparison Strings to either upper case or lower case before calling countMatches() with these Strings. The countMatches() method takes two arguments. The first argument is the main String that you want search. The second argument is the search String that you want to find in your main String.

The CountMatchesTest class demonstrates this. It reads in a String from a File (using FileUtils of Commons IOS) and displays this String. It converts the String to lower case so that a case-insensitive count can be performed. It calls StringUtils.countMatches() and returns the number of times the word "the" is found in the String. It outputs this count to the console.

CountMatchesTest.java

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class CountMatchesTest {

	public static void main(String[] args) throws Exception {

		String str = FileUtils.readFileToString(new File("test.txt"));
		System.out.println("String:\n" + str);
		str = StringUtils.lowerCase(str);
		int countThe = StringUtils.countMatches(str, "the");
		System.out.println("\"the\" count: " + countThe);
	}

}

The test.txt file is shown here:

test.txt

Hickory Dickory Dock
The mouse ran up the clock
The clock struck one
The mouse ran down
Hickory Dickory Dock

The console output of CountMatchesTest can be seen here:

Results

String:
Hickory Dickory Dock
The mouse ran up the clock
The clock struck one
The mouse ran down
Hickory Dickory Dock

"the" count: 4