Code Examples

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

Counting characters in Java

There are many ways for counting the number of characters in a String.

Below a simple/naive approach:

public class CountChars { public static void main(String[] args) { System.out.println(count("He-Man is a fictional superhero")); } private static int count(String text) { int count = 0; for (int i = 0; i < text.length(); i++) { count++; } return count; } }