Find Number of Words in a String in Java

Finding number of a words in a String is a common problem in text processing. The Java string API and regular expression support in Java makes it a trivial problem.

Finding Word Count of a String in Java

The following Java program uses split() method and regular expressions to find the number of words in a string. Split() method can split a string into an array of strings. The splitting is done at substrings which matches the regular expression passed to the split() method. Here we pass a regular expression to match one or more spaces. We also print the individual words after printing the word count.

// Java program to find word count of a string
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WordCount {
  
    public static void main(String[] args) throws IOException {
        System.out.print("Please enter a string: ");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String string = reader.readLine();
        
        String[] words = string.split("\\s+"); // match one or more spaces
        
        System.out.println("\""+string+"\""+" has "+words.length+" words");
        System.out.println("The words are, ");
        for(int i =0;i<words.length;i++) {
            System.out.println(words[i]);
        }
    }
}

The above examples works even with strings which contain multiple consecutive spaces. For example, the string "This     is a       test" returns a count of 4. That is the beauty of regular expressions!