lang3

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.

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button