Lesson 6 of 23

wc -w

wc -w: Count Words

wc -w counts the number of words. A word is a sequence of non-whitespace characters separated by spaces, tabs, or newlines:

$ echo "hello world foo" | wc -w
3

Your Implementation

Write int count_words(const char *s) that counts the words using a state machine: track whether you are currently inside a word or between words.

int count_words(const char *s) {
    int n = 0;
    int in_word = 0;

    while (*s) {
        if (*s == ' ' || *s == '\t' || *s == '\n') {
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            n++;    // first character of a new word
        }
        s++;
    }
    return n;
}

The key insight: you increment the counter once per word, at the moment you transition from "not in word" to "in word". Without the in_word flag, you would count each character.

State Machines in C

This two-state model (in_word / not_in_word) is a classic example of a finite state machine implemented with a boolean flag. Many text processing problems in C follow this pattern:

  • wc -w: count transitions into "word" state
  • Tokenizers: accumulate characters while in "token" state
  • Parsers: track whether you are inside a string, comment, etc.

Your Task

Implement count_words using the state machine approach.

TCC compiler loading...
Loading...
Click "Run" to execute your code.