In this tutorial, I am going to explain a java program to count number of words in a string.
Given an input string, write a code to count number of words in a string. The words in a string are separated by space(‘ ‘).
For example –
Example 1 –
Input – “Java Programming question”
Output – 3
Example 2 –
Input String – “Programming Tutorials”
Output – 2
Algorithm to Count Number of Words in a String
To count a number of words in a String. Traverse a string and check if a current character is a space and the next character is not space then increment the word count by 1.
1 2 3 4 5 6 7 8 |
//Traverse a string for(int i = 0; i < len-1; i++) { //Current character is space and next character is not a space if(str[i] ==' ' && str[i+1] != ' ') { count++; } } |
Java Program to Count Number of Words in a String
Let’s write a java code for the discussed algorithm. In this programming example, we are writing a code a word count program in java.
The time complexity of this approach is O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//Count Number of Words in a String : Java Code public class CountNoOfWords { public static void main(String[] args) { String str = "Java programming question"; System.out.println(countWord(str)); } public static int countWord(String str) { //Filter blank string if(str.trim().isEmpty()) { return 0; } int wordCount = 1; int len = str.length(); for(int i = 0; i < len-1; i++) { if(str.charAt(i) == ' ' && str.charAt(i+1) != ' ') { wordCount++; } } return wordCount; } } |
Find first non-repeating character in a string
METHOD 2:
Java Program to Count Number of Words in a String using Split
Using the split() method in java we can solve this problem in single line of code. In this solution, we use the regular expression “\\s+” to split the string on whitespace. The string split method returns an array, if we print the length of an array that is the number of words in a given string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Using split method in java public class CountNoOfWords { public static void main(String[] args) { String str = "Java programming question"; if (str == null || str.isEmpty()) { return 0; } //print number of words System.out.println(str.split("\\s+").length); } } |
Video Tutorial
In this video tutorial, I have explained the logic of counting number of words in a string.
How to Count Number of Words in a String – Java