数一句话里有几个单词。单词之间隔着一个或几个空格,开头、结尾也可能有空格;空字符串、全是空格都是 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;
}
写好了先点「运行」试试示例,没问题再点「提交」。