basics · beginner · ~15 min

Count whitespace-separated words

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

Challenge

Implement int count_words(const char *s) returning the number of maximal runs of non-whitespace characters in s. Whitespace is any character for which isspace returns true.

Examples

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

Edge cases

  • Leading and trailing whitespace.
  • Multiple consecutive spaces, tabs, newlines.
  • All-whitespace input.

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

Null-terminated ASCII string.

Output format

The word count as int.

Constraints

Single pass; O(1) extra memory.

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.