Thursday, January 4, 2024

Count Number of Words in a String Java Program

Write a Java program to count the number of words in a String is asked quite frequently in Java interviews. To test the logical thinking of the candidates it is often asked to write this program without using any of the String functions.

Java Program to count number of words in a String

Here three ways are given to count number of words in a String in Java. All of these ways take care of any number of spaces in between the words even the spaces at the beginning or at the end.

  • First method countWords() uses char array (this logic doesn't use any of the inbuilt String method). Logic used in the method works fine even if there are extra spaces in the passed String and the correct count of the words in the String is given.
  • Second method countWordsUsingSplit() uses the String split() method to count number of words.
  • Third method countWordsUsingStream() uses the Java Stream API to count number of words.

Let's see the Java code first and later explanation of the code logic.

public class StringWordCount {
  public static void main(String[] args) {
    System.out.println("Word Count- " + countWords("   Life    is    beautiful  "));
        
    System.out.println("Count using split logic " + countWordsUsingSplit("         Life     is       beautiful  "));
    
    System.out.println("Count using Java Stream " + countWordsUsingStream("   Life    is    beautiful  "));
  }
    
  private static int countWords(String str){        
    int c = 0;
    char ch[]= new char[str.length()];
    for(int i = 0; i < str.length(); i++){
      ch[i] = str.charAt(i);
      /**
       * logic here is if the character read is not a space or tab and the character read before the 
       * current char was either space or tab character that means one whole word is read so 
       * increment the count.  
       */
      if(((i > 0) && (ch[i] != ' ' && ch[i] != '\t') 
          && (ch[i-1] == ' ' || ch[i-1] == '\t')) 
          || ((ch[0] != ' ' && ch[0] != '\t') && (i == 0)))
        c++;
    }
    return c;
  }
    
  /**
  * This method counts using String split method 
  * @param str
  * @return
  */
  private static int countWordsUsingSplit(String str){
    // here split method is used with regex pattern of any number of spaces
    // so it will retrun a string array with the words
    String[] test = str.trim().split("\\s+");
    return test.length;
  }
  
  /**
  * This method counts using Java Stream API
  * @param str
  * @return
  */
  private static long countWordsUsingStream(String str){
	  // here split method is used with regex pattern of any number of spaces
	  // trim() is used to remove spaces in the beginning and at the end
	  long count = Stream.of(str.trim().split("\\s+")).count();
	  
	  return count;
  }
}

Output

Word Count- 3
Count using split logic 3
Count using Java Stream 3

Count number of words in a String program logic

In the first method countWords() the idea is; if the character read is not a space or tab and the character read before the current char was either space or tab character that means one whole word is read so increment the count. This is the condition doing that

(ch[i] != ' ' && ch[i] != '\t') && (ch[i-1] == ' ' || ch[i-1] == '\t')

For example if program is reading the string “life is” when the index comes to 'i' the character before 'i' would be either space or tab, that means one word is already read (which in this case would be “life”) thus count will be incremented.

We may miss to count the first word, this condition (ch[0] != ' ' && ch[0] != '\t') && (i == 0) takes care of that.

Second way of counting number of words in a String uses the split method of string. Split() method takes a regex pattern as a parameter here we are passing “//s+” which will mean any number of spaces. So the condition becomes; split the word on any number of spaces in between. It returns a String array whose length will be the count of words in a string.

In the third method, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then count() method of Java Stream API is used to return the count of elements in this stream.

That's all for this topic Count Number of Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Java Program to Check Prime Number

You may also like-

  1. Bubble Sort Program in Java
  2. Matrix Subtraction Java Program
  3. Package in Java
  4. Encapsulation in Java
  5. Marker interface in Java
  6. Creating Custom Exception Class in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Race Condition in Java Multi-Threading