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 two ways are given to count number of words in a String in Java.
- First method (countWordsForwardLogic) uses char array (this logic doesn't use any of the inbuilt String method).
- Second method countWordsUsingSplit() uses the String split() method.
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 "));
}
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;
}
}
Output
Word Count- 3
Count using split logic 3
Here it can be seen that even if there are extra spaces in the passed String that is accounted in the logic and the correct count of the words in the String is given.
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')
As example- if 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.
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.
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
You may also like-