Home Java Beginners Word Count



Word Count
Posted on: July 6, 2007 at 12:00 AM
Here providing you an example that counts the number of occurrences of a specific word in a string.

Word Count

     

This example counts the number of occurrences of  a specific word in a string. Here we are counting the occurrences of word "you" in a string. To count it we are using countMatches() method.

The org.apache.commons.lang.StringUtils class extends the Object class and defines certain words related to String handling such as null for null,"" for a zero-length string, ' ' for space characters, Charecter.isWhitespace(char) for whitespace and String.trim() for trim. The StringUtils class handles null input strings.

The method used:

countMatches(String str,String sub): This method counts how many times the string sub appears in the String str. This method returns zero if  StringUtils.countMatches(null, *), StringUtils.countMatches("", *) ,StringUtils.countMatches("abba", null),StringUtils.countMatches("abba", "") , and StringUtils.countMatches("abba", "x"). The parameters used  as "str" is String to be checked and "sub" is substring to be count.


 The code of the program is given below:

import org.apache.commons.lang.StringUtils;
 
public class WordCountExample 
{  
  public static void main(String[] args)
  {
  String string = "How r you?R you fine?Where are you going?";  
  System.out.println(StringUtils.countMatches(string,"you")
" occurrences of the word 'you' in '" + string +
  "' is found.");
  }
}

The output of the program is given below:

C:\rajesh\kodejava>javac WordCountExample.java
C:\rajesh\kodejava>java WordCountExample
3 occurrences of the word 'you' in 'How r you?R you fine?
Where are you going?' is found.

Download this example

Related Tags for Word Count:
capachestringcomclassnullobjectcountmethodwordcharwhitespaceusingailengthcharactercharactersdefineforctematchtrimtohandlingextendlanwordsexteilspaceitextendszerolsliulimceinasmnttrjaceclesendcommonmeobjrelwhitesrectsuspdefinesespatpacraclatehitishallandarcommonsactstrrelaterdsrtxtutilutiutilszssriringrdthswcerst.comapendsfinendsjeorgndonomo


More Tutorials from this section

Ask Questions?    Discuss: Word Count   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.