
Count Words in Java
Sure! Let's see how to count words in Java ?:
Simple Java Program to Count Words in a String:
import java.util.Scanner;public class WordCount { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a sentence: "); String sentence = scanner.nextLine(); // Read the full line // Split the sentence into words String[] words = sentence.trim().split("\\s+"); // Count the number of words int wordCount = words.length; System.out.println("Number of words: " + wordCount); scanner.close(); }}
Explanation:
trim()
: Removes spaces at the beginning and end of the string.split("\\s+")
: Splits the string by one or more spaces (also handles multiple spaces).words.length
: Gives the total number of words.
Sample Output:
Enter a sentence: Java is simple and powerful Number of words: 5
Would you like me to also show a version that ignores empty input or special characters? ?
It’s a tiny upgrade! ?