Java Program to Count Number of Words in a String

In this post we’ll see Java program to count number of words in a String. You can use split() method provided by the Java String class with the regular expression “\\s+” to match any number of white spaces. split() method returns an array which contains each substring of this string that matches the given expression. The length of this array will be the count of words in the String.

If you are specifically ask to write the Java program without using any API method then you can use the logic where you check each character of the string whether it is a space or not. If it is a space that means word has ended then you can increment the count.

Count number of words in a String Java program

The following Java program shows both of the ways to count number of words in a String as discussed above.

public class CountWords {

  public static void main(String[] args) {
    CountWords.stringWordCount("This program is to count words");
    
    CountWords.wordCountUsingSplit("count words using   split  ");
  }
	
  public static void stringWordCount(String str){
    int count = 1;
    for(int i = 0; i < str.length() - 1; i++){
      // If the current char is space and next char is not a space
      // then increment count
      if((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')){
        count++;
      }
    }
    System.out.println("Count of words in String - "  + count);
  }
	
  // This method uses split method to count words
  public static void wordCountUsingSplit(String str){
    // regex "\\s+" matches any number of white spaces 
    String[] test = str.trim().split("\\s+");
    System.out.println("Count of words in String - "  + test.length);
  }
}

Output

Count of words in String - 6
Count of words in String – 4

Related Posts

That’s all for the topic Java Program to Count Number of Words in a String. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.