Friday, 12 June 2015

Count number of words in a String - Java Program

Write a program to count the 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. Here I am giving three ways of doing it, first two using char array and String and third one using the String split() method.

In the program the if condition may look a little intimidating at the first glance but rest assured once you get the logic it is really very easy to do. In the first method countWordsForwardLogic() the idea is that once the last character with in a word is read it will be followed by a space or tab character. If we have a string “life is” and while reading the first world life when the character ‘e’ is read after that space will come. That’s what is checked in this piece of condition –
(ch[i] != ' ' && ch[i] != '\t') && (ch[i+1] == ' ' || ch[i+1] == '\t')

Here i denotes the index of the current character read and i+1 will be the character after that. So if a word is ending then ch[i] should not be a space and the next character ch[i+1] should be space or tab character.

Since we are reading one character ahead also so we do need to check that it doesn’t go beyond the length of the String thus the condition -

i+1 < str.length()

Last ‘or’ condition (i+1 == str.length() && ch[i] != ' ') checks for the last word otherwise the last word may not be counted in case there are no spaces after the last word.

In the second way of counting the words using method countWordsBackwardLogic() 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')

As exp- if we the program is reading the string “life is” when the index comes to i in is the character before would be space or tab, that would mean one word is already read (which in this case would be “life”) thus count will be incremented.

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

Third way of doing it 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.

Here is the whole program –

public class StringWordCount {

    public static void main(String[] args) {
        System.out.println("Count using forward logic " + countWordsForwardLogic("         Life     is       beautiful"));
        
        System.out.println("Count using backward logic " + countWordsBackwardLogic("    Life     is       beautiful  "));
        
        System.out.println("Count using split logic " + countWordsUsingSplit("         Life     is       beautiful  "));
    }
    
    /**
     * This method will count using forward logic
     * @param str
     * @return
     */
    private static int countWordsForwardLogic(String str){        
        int c = 0;
          char ch[]= new char[str.length()];
          for(int i = 0; i < str.length(); i++){
              ch[i] = str.charAt(i);
              // this check is required so that 
              // we don't try to read beyond the String length
              if(i+1 < str.length()){
                  // Since we are using one character ahead,
                  // we need to read it using extra logic
                  ch[i + 1] = str.charAt(i + 1);
              }
              /**
               * logic here is after reading the last character in a word it 
               * should be followed by either
               * space or tab, in that case increment the count 
               */
              if((i+1 < str.length() && (ch[i] != ' ' && ch[i] != '\t') && 
              (ch[i+1] == ' ' || ch[i+1] == '\t')) 
              || (i+1 == str.length() && ch[i] != ' ')){
                  c++;
              }
          }
          return c;

    }
    
    /**
     * This method will count using backward logic
     * @param str
     * @return
     */
    private static int countWordsBackwardLogic(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 will count 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;

    }
}

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!


Related Topics

  1. Check whether a given String/Number is a palindrome or not
  2. Count total number of times each character appears in a String
  3. How to find all the permutations of the given String
  4. Check if given strings are anagram or not
  5. Checking number prime or not Java program
  6. Factorial program in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment