Home » Core Java » apache » commons » lang3 » Word counter

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Word counter

This is an example of how to count the words of a String paragraph, using the org.apache.commons.lang3.StringUtils class. This class provides operations on String that are null safe. Counting the words of a paragraph implies that you should:

  • Create a String that is a paragraph.
  • Create a String word that is the word to search in the paragraph.
  • Use the countMatches method of StringUtils method that counts the number of occurrences of one String in another.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

import org.apache.commons.lang3.StringUtils;

public class WordCounter {
	
	public static void main(String[] args) {
		
		// String with our paragraph
		String paragraph = "Java Code Geeks (JCGs) is an independent online community focused on creating the" 
		+ "ultimate Java-to-Java developers resource center; targeted at the technical architect, technical" 
	    + "team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, "
		+ "Scala, Android, SOA, Agile and Telecom communities with daily news written by domain experts, "
	    + "articles, tutorials, reviews, announcements, code snippets and open source projects.";
		
		// Declare the word you want to search
		String string = "Java";

		// Count word repetitions
		int counter = StringUtils.countMatches(paragraph, string);

		// Print the result
		System.out.println("Word <" + string + "> appeared " + counter + " times in the paragraph.");
	}
}

Output:

Word <Java> appeared 4 times in the paragraph.

  
This was an example of a word counter in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments