Core Java >> Strings


Count words in a String


If a Java program needs to count the number of words in a string then there are multiple ways to do so.
The following program shows how to count the number of words of a string.

Java word count program

package com.example;

/** This class is a Java tutorial for counting words in String
 *
 * @author Extreme Java
 */
public class Test{

	/** This method shows how to find the number of words in String
	 *
	 * @param args
	 */
	public static void main(String[] args){

		String str = "This is a test string";
		String[] count = str.split(" ");
		System.out.println(count.length);

	}
}

output:
5

Caution

Of course, the program assumes that the words in the string are separated by single white space. If your string has some other delimiter then use the same in the call to split method of String class.

Other Java Programming Tutorial
Java Interview Questions
Transitioning from Developer to Project Lead
Custom Exceptions in Java

Comments

Julio

January 19, 2012 9:23 pm

1. If we only want to count words this is short but wastes a lot of memory by creating the whole String array.
2. It would be trivial to improve b by using .split("\s*") to handle words separated by more than one space.

Theo Vosse

January 19, 2012 9:23 pm

1. Note that split() just uses a regular expression. E.g., you might like to use something like “[:;,.!? \t\r\n]+”. Note that the + is important. Splitting on \s* could split the string into characters; omitting it leads to empty words for two or more consecutive separating characters.
2. Don’t call the resulting array “count”; it’s misleading.

Leave Comment