basics · beginner · ~15 min

Count whitespace-separated words

Two-state finite-state machine (in-word vs not).

Challenge

Count how many words are in a string, where a word is any run of non-whitespace characters.

Task

Implement int count_words(const char *s) that returns the number of maximal runs of non-whitespace characters. A character is whitespace whenever isspace returns true (space, tab, newline, carriage return, form feed, vertical tab). Any amount of whitespace between or around words is ignored.

Input

A NUL-terminated ASCII string s.

Output

Returns the word count as an int.

Example

count_words("hello world")        ->   2
count_words("   spaced   out ")   ->   2     (extra spaces ignored)
count_words("oneword")            ->   1
count_words("")                   ->   0
count_words("   ")                ->   0     (all whitespace)
count_words("a b c d e")          ->   5

Edge cases

  • Leading/trailing whitespace does not add words.
  • Multiple consecutive separators (spaces, tabs, newlines) count as one gap.
  • Empty or all-whitespace input returns 0.

Rules

  • Single pass with O(1) extra memory; use isspace, not just a check for ' '.

Why this matters

Word counting is the smallest example of state-machine parsing in C. The same logic powers tokenisers, CSV readers, log analysers, and shell argument splitters.

Input format

A NUL-terminated ASCII string s.

Output format

The number of whitespace-separated words, as an int.

Constraints

Single pass, O(1) extra memory. Treat any isspace character as a separator.

Starter code

int count_words(const char *s) { /* TODO */ return 0; }

Common mistakes

Counting spaces and adding 1 — broken on leading/trailing space. Treating only ' ' as whitespace — must use isspace (covers tab, newline, CR, FF, VT).

Edge cases to handle

Empty; all whitespace; single word with no whitespace; multiple separators.

Complexity

O(strlen(s)).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.