Wednesday, June 22, 2005

Simplifying Java: How to Count the Number of Words in a String using Java (one-liner)

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);
}
}

[via Simple Thoughts]