basics · intermediate · ~15 min

Count words

Track transitions between two states while scanning.

Challenge

Count the words in a string using a two-state scanner.

Task

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.

Input

A NUL-terminated string s.

Output

Returns the number of words, as an int.

Example

count_words("the quick fox")     ->   3
count_words("  hi   there  ")    ->   2     (leading/trailing/multiple spaces ignored)
count_words("solo")              ->   1
count_words("")                  ->   0

Edge cases

  • Leading, trailing, and repeated whitespace must not inflate the count.
  • The empty string has 0 words.

Rules

  • Count the rising edge (whitespace -> non-whitespace), not every non-space character.

Input format

A NUL-terminated string s.

Output format

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

Constraints

Words are runs of non-whitespace; collapse repeated separators.

Starter code

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.