Home > Tutorial > Java Count Occurrences Sample Code

Java Count Occurrences Sample Code

The sample Java code below will search for the number of occurrences of a given String within another String. While this could have been done using the standard Java APIs, I really like the Apache Commons Lang API because it includes a class called StringUtils, which has some very helpful methods.

You will need to download and install the Apache Apache Commons Lang library. You will need to download and add to your build path. Since I am using Exclipse for Java development, I placed the jar in my lib/ folder and added the jar to my build path as seen below:

Java Count Occurrences Source Code

package com.jcd.java.tutorials;


import org.apache.commons.lang3.StringUtils;


public class JavaCountOccurrences 
{

	public static void main(String[] args) 
	{
		int count = 0;
		
		String sampleString = "<html><head><title></title></head><body><script></script><script></script><h1></h1><h2></h2><h2></h2><h3></h3><h3></h3><h3></h3><p></p><p></p><p></p><p></p></body></html>";
		
		count = numberOfElements(sampleString, "<h1>");
		System.out.println("\nOccurrences of h1: "+count);
		
		count = numberOfElements(sampleString, "<h2>");
		System.out.println("\nOccurrences of h2: "+count);
		
		count = numberOfElements(sampleString, "<h3>");
		System.out.println("\nOccurrences of h3: "+count);
		
		count = numberOfElements(sampleString, "<script>");
		System.out.println("\nOccurrences of script: "+count);
		
		count = numberOfElements(sampleString, "<p>");
		System.out.println("\nOccurrences of p: "+count);
		
		count = numberOfElements(sampleString, "<title>");
		System.out.println("\nOccurrences of title: "+count);

		count = numberOfElements(sampleString, "<dummy>");
		System.out.println("\nOccurrences of dummy: "+count);
	}
	
	//Return number of occurrences in a string
	public static int numberOfElements(String content, String element)
	{
		int ctr = StringUtils.countMatches(content, element);
		return ctr;
	}

}


Sample Java Count Occurrences Output


Occurrences of h1: 1

Occurrences of h2: 2

Occurrences of h3: 3

Occurrences of script: 2

Occurrences of p: 4

Occurrences of title: 1

Occurrences of dummy: 0



Java References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot