Last Updated: June 7, 2026
The spacing is what makes this nontrivial. A clean sentence like "hello world" has two words, but real input might start with spaces, end with spaces, or pack several spaces between words.
Consider " leading and trailing ". The extra spaces at the front and back should not add phantom words. The answer is still 3, for "leading", "and", and "trailing".
Define a word as a contiguous run of non-space characters. The task is then to count how many such runs appear, no matter how the spaces are arranged around them. Two methods follow. The first counts the points where a word begins. The second splits the string into pieces and counts the non-empty ones.
"multiple spaces here" has three such groups, so the answer is 3.0 → Neither contains a single non-space character, so there are no words to count.Every word begins exactly once, when a non-space character follows a space or the start of the string. Counting these starting points counts the words.
Walk through the string. A new word starts when the current character is not a space and the character just before it either does not exist or is a space. Counting these space-to-non-space transitions gives the word count and naturally ignores leading, trailing, and repeated spaces.
count to 0.1 to count.count.Input:
Start with count = 0. Index 0 is a space, so nothing happens. Index 1 is a, which is non-space and follows a space, so a word starts and count becomes 1. Indexes 2 and 3 are spaces, so nothing happens. Index 4 is b, which is non-space and follows a space, so count becomes 2. Index 5 is b, non-space but following another non-space, so no new word starts. After the scan, the answer is 2.
s. The loop visits each character once and does a constant amount of work.The transition scan counts words in place without building anything extra. A different way leans on splitting the string and counting the pieces that survive.
Most languages can split a string into pieces wherever whitespace appears, and each piece is a candidate word. The complication is that leading, trailing, or repeated spaces produce empty pieces, so counting every piece overcounts.
Trim the surrounding spaces and split on one or more spaces to leave only the real words. Counting the resulting non-empty pieces gives the word count. This trades a bit of extra memory for code that reads closer to the problem description.
0 because there are no words.Input:
Trimming " a bb " removes the leading and trailing spaces, leaving "a bb". Splitting that on runs of spaces produces the two pieces "a" and "bb". Both pieces are non-empty, so the answer is 2.
s. Trimming and splitting both scan the string once.