basics · beginner · ~15 min
Two-state finite-state machine (in-word vs not).
Count how many words are in a string, where a word is any run of non-whitespace characters.
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.
A NUL-terminated ASCII string s.
Returns the word count as an int.
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
isspace, not just a check for ' '.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.
A NUL-terminated ASCII string s.
The number of whitespace-separated words, as an int.
Single pass, O(1) extra memory. Treat any isspace character as a separator.
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.