Home »
Java Programs »
Core Java Example Programs
Java program to count total number of words in a string
Problem statement
This program will count total number of words in a string in Java. In this program we will read a string from the user and count total number of words in that.
Counting total number of words in a string
The logic behind to implement this logic - Check two consecutive characters, if first character is space and next is not space, if the condition is true we will increase the counter.
Example
Input:
Enter string: Hello world
Output:
Total number of words in string are: 2
Count Words in a String using Java program
//Java program to count words in a string.
import java.util.Scanner;
class CountWords
{
public static void main(String args[])
{
String text;
int countWords=0;
Scanner SC=new Scanner(System.in);
System.out.print("Enter string: ");
text=SC.nextLine();
//word count
for(int i=0; i<text.length()-1; i++)
{
if(text.charAt(i)==' ' && text.charAt(i+1)!=' ')
countWords++;
}
System.out.println("Total number of words in string are: "+ (countWords+1));
//since last word does not contain and character after that
}
}
Output
Enter string: Hello world
Total number of words in string are: 2
Core Java Example Programs »