Kodewick
Start learning →
Basic←→0 / 50

Count words

#042Basicin_word == 08 min

Count the words in a sentence. Words are split by one or more spaces, and there may be spaces at the start or end; an empty string or all spaces is 0 words. Write count_words(s) to return the count. "a bb ccc" has 3, and " x yy " has 2. In the starter, in_word remembers if we are inside a word right now.

Examples
count_words("a bb ccc")→3
count_words(" x yy ")→2
count_words("")→0
The functionint count_words(const char *s)
main.c
int count_words(const char *s) {
    int count = 0;
    int in_word = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == ' ') {
            in_word = 0;
        } else {
            // your code here: just stepped from a space into a new word, so count one
        }
    }
    return count;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.