This post originated from an RSS feed registered with Web Buzz
by Angsuman Chakraborty.
Original Post: Simplifying Java: How to Count the Number of Words...
Feed Title: LinkBlog - Java, Bioinformatics, Outsourcing, Web
Feed URL: http://feeds.feedburner.com/Linkblog-JavaBioinformaticsOutsourcingWeb
Feed Description: A LinkBlog of my web travels. It includes links of my interests which are Java, Bioinformatics, Software Outsourcing, Web Technologies, Diabetes, Global Politics etc.
Java is a language of choice for millions of developers worldwide. In a series of articles I will show simple tips and techniques which make Java extremely powerful and yet simple to use. Today's article is about using regex, a pattern matcher incorporated in Java (from 1.4 I believe).
Here is a sample code (line in bold) to count the number of words in any amount of text. The sample program counts the number of words in the argument to the program. The argument must be quoted to ensure separate words are clubbed together in a single sentence by the operating system.
public class WordCount { public static void main(String args[]) { System.out.println(java.util.regex.Pattern.compile("[\\w]+").split(args[0].trim()).length); } }