Kodewick
学びはじめる →
基礎←→0 / 50

単語の数を数える

#042基礎in_word == 0約 8 分

文の中の単語の数を数えます。単語の間は空白 1 つかいくつかで、先頭や末尾にも空白があるかもしれません。空文字列や空白だけなら 0 個です。単語の数を返す count_words(s) を書きましょう。たとえば "a bb ccc" は 3 個、" x yy " は 2 個です。初期コードの in_word は「今、単語の中にいるか」を表します。

例
count_words("a bb ccc")→3
count_words(" x yy ")→2
count_words("")→0
関数int 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 {
            // ここにコードを書く:空白から新しい単語に入ったところで 1 つ数える
        }
    }
    return count;
}
Ctrl + Enter でも実行できます
結果

実行すると例で試せます。よさそうなら提出しましょう。