Java Program to Count Words in a Sentence

  • 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;

/**
 * Java Program to Count Words in Sentence
 */
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