basics · intermediate · ~15 min
Track transitions between two states while scanning.
Count the words in a string using a two-state scanner.
Implement int count_words(const char *s) that returns the number of whitespace-separated words in s. A word is a maximal run of non-whitespace characters; runs of spaces, tabs, or newlines separate words. Track an in-word / out-of-word state and count each time you transition into a word. No main — the grader calls it.
A NUL-terminated string s.
Returns the number of words, as an int.
count_words("the quick fox") -> 3
count_words(" hi there ") -> 2 (leading/trailing/multiple spaces ignored)
count_words("solo") -> 1
count_words("") -> 0
A NUL-terminated string s.
The number of whitespace-separated words, as an int.
Words are runs of non-whitespace; collapse repeated separators.
int count_words(const char *s) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.