Counting Number of Words in given String

Posted by Somesh Shinde On Sunday, 26 June 2016 0 comments

How to count a number of words in given String in Java?


Can you write a method in Java which accepts a String argument and returns a number of words in it? A word is a sequence of one or more non-space character i.e. any character other than '' (empty String). This should be your method signature:

public int count(String word);

This method should return 1 if the input is "Java" and return 3 if the input is "Java, C++, Python". Similarly a call to wordCount("    ") should return 0.


Solution - Counting words in String


The solution of this problem is very simple if you know a little bit of regular expression and how to split String in Java using regex (see here). Since problem says that words are separated by white space, which could be space or tabs. So if you split the String by whitespace as shown here, you can get an array of String which is nothing but words.  Now the length of this array is your number of words, just return that.

Though, you need to be a little bit careful because there is also a possibility of more than one space between two words. So simply using a regular expression to catch space or tab will not be enough, you need to use a greedy regular expression to catch multiple spaces as well.

In Java, you can use the regular expression pattern "\\s+" to catch multiple spaces. The "\s" is a character class to find white space, which could match both space and tabs and "+" makes it greedy because it will match one or more of "\s" pattern i.e. one or more space. Now, since you need to escape the "\"  backward slash in Java, the whole pattern becomes"\\s+". Se Mastering regular expression to learn more about regex in Java.
Java Program to count number of words in String

/**
 * Java Program to count number of words in a given
 * sentence. Words are separated by whitespace in
 * String.
 * @author WINDOWS 8
 *
 */
public class StringCounter {


    public static void main(String[] args) {
        
        // testing with non-empty String
        String input = "Java is great";
        int numOfWords = count(input);
        
        System.out.println("input: " + input);
        System.out.println("count of words: " + numOfWords);
        
        // testing with empty String
        input = "";
        numOfWords = count(input);
        
        System.out.println("input: " + input);
        System.out.println("count of words: " + numOfWords);
        
        // testing with null String
        input = null;
        numOfWords = count(input);
        
        System.out.println("input: " + input);
        System.out.println("count of words: " + numOfWords);

    }
    
    /**
     * Return the number of words in given String
     * @param sentence, words are separated by whitespace
     * @return count of words in sentence
     */
    public static int count(String sentence){
        if(sentence == null || sentence.isEmpty()){
            return 0;
        }
        
        String[] words = sentence.split("\\s+");
        return words.length;
    }


}

Output:
input: Java is great
count of words: 3
input: 
count of words: 0
input: null
count of words: 0


That's all about how to count a number of words in a given String in Java. The regular expression trick really solves this problem in a couple of lines, but as a challenge, can you solve this problem without using regular expression? If you go on real interview, that would be surely a follo-up questions given how easy the split() method solves this problem. So, why not try it now? You can also check the solution here, once you have tried and solved it yourself.


Other String coding Interview questiosns from Programming Interviews:
  • How to reverse String in Java without StirngBuffer? (solution)
  • How to count vowels and consonants in given String? (solution)
  • How to find duplicate characters on String? (solution)
  • How to check if a Stirng is palindrome in Java? (solution)
  • How to reverse words in a given String in Java? (solution)
  • How to print all permutations of a String using recursion? (solution)

0 comments:

Post a Comment