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 three ways are given to count number of words in a String in Java. All of these ways take care of any number of spaces in between the words even the spaces at the beginning or at the end.
- First method
countWords()
uses charAt() method to get each character of the String. Logic used in the method works fine even if there are extra spaces in the passed String and the correct count of the words in the String is given. - Second method
countWordsUsingSplit()
uses the String split() method to count number of words. - Third method
countWordsUsingStream()
uses the Java Stream API to count number of words.
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 ")); System.out.println("Count using Java Stream " + countWordsUsingStream(" Life is beautiful ")); } private static int countWords(String str){ if(str.isBlank()) { return 0; } int c = 0; for(int i = 0; i < str.length(); i++){ /** * logic here is if the current character is not a space and the character read before the * current char was a space that means one whole word is read so increment the count. * Or part is to ensure correct working even if there are spaces in the beginning */ if((i > 0 && (str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' )) || ((i == 0) && (str.charAt(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; } /** * This method counts using Java Stream API * @param str * @return */ private static long countWordsUsingStream(String str){ // here split method is used with regex pattern of any number of spaces // trim() is used to remove spaces in the beginning and at the end long count = Stream.of(str.trim().split("\\s+")).count(); return count; } }
Output
Word Count- 3 Count using split logic 3 Count using Java Stream 3
Count number of words in a String program logic
In the first method countWords() the idea is; if the current character is not a space and the character read before the current char was a space that means one whole word is read so increment the count. This is the condition doing that
(str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' )
For example if program is reading the string “life is” when the index comes to 'i' (in "is") the character before 'i' would be either space or tab, that means one word is already read (which in this case would be "life") thus count will be incremented.
We may miss to count the first word, this condition (i == 0) && (str.charAt(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.
In the third method, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then count() method of Java Stream API is used to return the count of elements in this stream.
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-