Pages

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. This is 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 always use the Cracking the Coding Interview, it contains 190 programming questions and solutions on every important topic e.g. String, array, linked list, hash table, binary tree and other data structures.

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.

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.