๐Ÿ” Java How-To Examples
Estimated reading: 3 minutes 34 views

๐Ÿ”ข Java: How to Count Words in a String


๐Ÿงฒ Introduction โ€“ Why Count Words in Java?

Whether you’re building a text editor, analyzing user input, or creating a word frequency counter, knowing how to count words in a string is a practical skill in Java.

In this guide, you’ll learn:

  • How to split a string into words
  • Count words using split() and Scanner
  • Handle edge cases like multiple spaces or punctuation

๐Ÿงฎ Method 1: Count Words Using split(" ")

public class WordCounter {
    public static void main(String[] args) {
        String text = "Java is a powerful programming language";
        String[] words = text.trim().split("\\s+");
        System.out.println("Word count: " + words.length);
    }
}

โœ… Explanation:

  • trim() removes leading/trailing spaces.
  • split("\\s+") splits the string by one or more whitespace characters.
  • The length of the array gives the word count.

๐Ÿ“˜ Method 2: Count Words Using Scanner

import java.util.Scanner;

public class WordCountScanner {
    public static void main(String[] args) {
        String text = "Java makes software development easier";
        Scanner scanner = new Scanner(text);
        
        int count = 0;
        while (scanner.hasNext()) {
            scanner.next();
            count++;
        }
        scanner.close();
        System.out.println("Word count: " + count);
    }
}

โœ… Explanation:

  • Scanner treats white-space separated tokens as words.
  • hasNext() checks if more tokens are available.
  • Each next() represents a word.

๐Ÿงช Edge Case Handling Example

String messyText = "   Multiple   spaces    and tabs\tare here  ";
String[] words = messyText.trim().split("\\s+");
System.out.println("Word count: " + words.length);

๐Ÿ’ก Handles:

  • Multiple spaces
  • Tabs (\t)
  • Leading/trailing white space

๐Ÿ“Š When to Use Which Method?

MethodBest For
split("\\s+")Simple, fast word count
ScannerToken-based parsing, flexible extension
Loop with regexAdvanced use-cases (punctuation handling, etc.)

๐Ÿ’ก Tips

  • โœ… Always trim() the string to clean leading/trailing spaces.
  • โš ๏ธ Be cautious of empty strings or multiple consecutive spaces.
  • โœ… Use regular expressions (\\s+) to avoid splitting too strictly.

๐Ÿ“Œ Summary โ€“ Word Count in Java

Counting words in Java is a simple yet essential task for many applications involving text processing. Whether you’re parsing input, processing text files, or analyzing user data โ€” this logic is a building block.

๐Ÿงพ Key Takeaways:

  • Use split("\\s+") for reliable whitespace-based word splitting
  • Use Scanner for token-based parsing
  • Always trim() strings before splitting
  • Handle punctuation and special characters as needed

โ“FAQs โ€“ Java Word Count

โ“ How does split("\\s+") work?

It uses regex to split by one or more whitespace characters, covering spaces, tabs, and newlines.

โ“ Can I use this to count words in a file?

Yes! Read file content into a string using Files.readString() or Scanner, then apply the same logic.

โ“ What if the string has punctuation?

To ignore punctuation, clean the string using replaceAll("[^a-zA-Z ]", "").

โ“ Will split(" ") work?

It works, but wonโ€™t handle multiple spaces or tabs properly. Use split("\\s+") instead.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Count Words

Or Copy Link

CONTENTS
Scroll to Top