basics · beginner · ~15 min
Two-state finite-state machine (in-word vs not).
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.
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
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.
Null-terminated ASCII string.
The word count as int.
Single pass; O(1) extra memory.
int count_words(const char *s) { /* TODO */ return 0; }
Counting spaces and adding 1 — broken on leading/trailing space. Treating only ' ' as whitespace — must use isspace (covers tab, newline, CR, FF, VT).
Empty; all whitespace; single word with no whitespace; multiple separators.
O(strlen(s)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.