Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Count Words in Java

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! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql