Java Program to Count Words in a Sentence

Here is a Java program to count words in a sentence using split method. To count the number of words in a sentence, we first take a sentence as input from user and store it in a String object. Words in a sentence are separated by space character(" "), hence we can use space as a delimiter to split given sentence into words. To split a string to multiple words separated by spaces, we will call split() method.

public String[] split(String regex);

split() method returns an array of Strings, after splitting string based of given regex(delimiters). To fine the count of words in sentence, we will find the length of String array returned by split method.


Java program to find the count of words in a sentence

package com.tcc.java.programs;

import java.util.Scanner;

public class WordCount {
    public static void main(String args[]) {
        String str;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a Sentence");
        str = scanner.nextLine();

        // Printing number of words in given sentence
        System.out.println("Number of Words = " 
            + str.split(" ").length);
    }
}
Output
Enter a Sentence
I Love Java Programming
Number of Words = 4

Recommended Posts
Java Program to Find Count of Each Character in a String
Java Program to Count Number of Digits in a Number
C++ Program to Count Zeros, Positive and Negative Numbers
C++ Program to Count Words in Sentence
C++ Program to Count Number of Vowels, Consonant, and Spaces in String
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Delete a Word from Sentence
Java Program to Delete All Spaces from a String
Java Program to Delete all Vowel Characters from String
Java Program to Concatenate Two Strings
Java Program to Find Length of a String
All Java Programs