數一句話裡有幾個單詞。單詞之間隔著一個或幾個空格,開頭、結尾也可能有空格;空字串、全是空格都是 0 個。寫 count_words(s) 返回單詞個數。比如 "a bb ccc" 是 3 個," x yy " 是 2 個。模板裡 in_word 記的是「現在是不是在一個單詞裡」。
count_words("a bb ccc")→3count_words(" x yy ")→2count_words("")→0int count_words(const char *s)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 {
// 在這裡寫:剛從空格走進一個新單詞,就數一個
}
}
return count;
}
寫好了先點「執行」試試示例,沒問題再點「提交」。