This is an example of how to count the words of a String paragraph, using theorg.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
countMatchesmethod ofStringUtilsmethod 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 paragraphString 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 searchString string = "Java";// Count word repetitionsint counter = StringUtils.countMatches(paragraph, string);// Print the resultSystem.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 aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.



