Friday, September 6, 2024

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

Can you write a method in Java that accepts a String argument and returns a number of words in it? A word is a sequence of one or more non-space characters 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. 

This is also one of the several String algorithmic questions you can expect in a programming job interview.  This is used to test the coding skills of the candidate and that's why it's very important to prepare for these questions anytime you go for an interview.

Many programmers have personal collections of such questions which they revise every time they go for a Programming job interview, but if you don't have any yet, then don't worry. 

You can also use the Cracking the Coding Interview, which contains 190 programming questions and solutions on every important topic like String, array, linked list, hash table, binary tree, and other data structures.


While I will use regular expression to solve this problem you can also solve it without regular expression as shown below:

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






Solution - Counting words in String

The solution to 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 the 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 a 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 the "\s" pattern i.e. one or more space. 

Now, since you need to escape the "\"  backward slash in Java, the whole pattern becomes "\\s+". You can further see these Regular expression courses to learn more about regex in Java.


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



Java Program to count the number of words in String

Here is our complete Java program to count the number of words in a given String. 
/**
 * Java Program to count number of words in a given
 * sentence. Words are separated by whitespace in
 * String.
 * @author Javin
 *
 */
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 a real interview, that would be surely a follow-up question 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 questions from Programming Interviews:

Thanks for reading this article so far, if you found this Java programming tutorial useful then please share it with your friends. If you have any questions or doubts, please ask. 

2 comments:

  1. If there is a space in front and end then it will give wrong output. So before proceed to count we have to trim it then start your logic.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.