beginnerString ProblemsJava

Count the Number of Words in a Sentence

Count how many words a sentence contains, treating runs of spaces as one separator.

Quick Answer

Scan the sentence and count each place where a word starts — a non-space character that follows a space or the beginning of the string. Track whether you are currently inside a word so runs of multiple spaces still count as one gap. This runs in O(n) time and needs no splitting.

Problem Statement

Given a sentence, count how many words it contains. A word is any maximal run of non-space characters, so multiple spaces between words, or leading and trailing spaces, should not inflate the count.

For example, Java is fun has 3 words, and hello world has 2 words.

Input: A single string s representing a sentence.

Output: The number of words as an integer.

Examples

Example 1
Input:  "Java is fun"
Output: 3

Three words separated by single spaces.

Example 2
Input:  "  hello   world  "
Output: 2

Extra leading, internal and trailing spaces do not add to the count.

Constraints

  • 0 <= s.length <= 10^5
  • Runs of multiple spaces count as a single separator

Think Before You Code

Reveal the questions to ask yourself first
  • What exactly marks the start of a new word?
  • How do you avoid counting the same word twice when spaces repeat?
  • How do leading and trailing spaces affect the count?
  • Can you count without splitting the string into an array?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
A new word begins at a non-space character that comes right after a space or the string start.
Hint 2
Track a boolean for whether you are currently inside a word.
Hint 3
Increment the count only on the transition from outside a word to inside one.

Approach

Reveal the step-by-step approach

Count word beginnings in a single pass.

  1. Start count at 0 and a boolean inWord at false.
  2. For each character c:
    • If c is not a space and inWord is false, you just entered a new word: increment count and set inWord = true.
    • If c is a space, set inWord = false.
  3. Return count.

Counting only the transitions into a word means each word is counted once no matter how many spaces surround it.

Dry Run

Walk through the example step by step

Counting words in "Java is fun":

char | space? | inWord before | action            | count
-----+--------+---------------+-------------------+------
J    | no     | false         | start word, count | 1
a    | no     | true          | -                 | 1
v    | no     | true          | -                 | 1
a    | no     | true          | -                 | 1
(sp) | yes    | true          | inWord=false      | 1
i    | no     | false         | start word, count | 2
s    | no     | true          | -                 | 2
(sp) | yes    | true          | inWord=false      | 2
f    | no     | false         | start word, count | 3
u    | no     | true          | -                 | 3
n    | no     | true          | -                 | 3
final: 3

Solution

Reveal the full Java solution
public class WordCount {
    public static int countWords(String s) {
        int count = 0;
        boolean inWord = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != ' ') {
                if (!inWord) {
                    count++;
                    inWord = true;
                }
            } else {
                inWord = false;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countWords("Java is fun"));       // 3
        System.out.println(countWords("  hello   world  ")); // 2
    }
}

The inWord flag records whether the scan is currently inside a word. A word is counted only when a non-space character follows a gap (or the start), so repeated spaces never add extra words and leading or trailing spaces are ignored. Because it never builds an array, the method uses constant extra space. To treat tabs and newlines as separators too, swap c != ' ' for !Character.isWhitespace(c).

Time: O(n) where n is the string lengthSpace: O(1)

Common Mistakes

  • Counting spaces and adding one, which breaks on multiple or trailing spaces.
  • Splitting on a single space so empty strings from double spaces get counted.
  • Forgetting to reset the in-word flag when a space is reached.

Edge Cases to Test

  • An empty string has 0 words.
  • A string of only spaces has 0 words.
  • A single word with surrounding spaces, like " hi ", has 1 word.

Interview Follow-Ups

  • How would you count words when tabs and newlines can also separate them?
  • How would you return the longest word in the same pass?
  • How would this compare to using split("\\s+") on a trimmed string?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us