【发布时间】:2020-06-03 22:06:08
【问题描述】:
我正在尝试编写一个程序来计算在字符串中找到的单词数,但是我编写的程序会计算空格数。我如何构建这个程序 - 尽可能高效 - 来计算字数?我该怎么说字符串包含 4 个单词和 8 个空格,或者如果它不包含单词而只包含空格?我错过了什么/做错了什么?
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
int count_words = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (isspace (text[i]))
{
count_words++;
}
}
printf("%i\n", count_words + 1);
}
【问题讨论】: