Counting words in Java

This is a simple way to count words in a string in Java.

StringTokenizer automatically takes care of whitespace for us, like tabs and carriage returns.

In some cases like in “he-man”, we’d want “he” and “man” to be different words, but since there’s no whitespace between them, the defaults fail us.

Fortunately, we can pass a delimiter into the constructor to make it works, how you can see:

public class CountWords {

	public static void main(String[] args) {
		System.out.println(count("He-Man is a fictional superhero"));
	}

	private static int count(String text) {
		return new StringTokenizer(text, " -").countTokens();
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *