Java Examples

java program to count number of words in a string using split

Table of Contents

CountWords.java

import java.util.Scanner;

/**
 * @author Candid Java
 */

public class CountWords {

 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter your text: ");
  String str = input.nextLine();
  int count = str.trim().split("[\\s]+").length;
  System.out.println("Your text has " + count + " word(s)");
  input.close();
 }

}

Output

Enter your text: WELCOME TO CANDID JAVA
Your text has 4 word(s)