如何计算c中每个字符串的单词和句子数量?

How to count the number of words and sentences per string in c?

这里是我为了 cs50 pset2 可读性而必须解决的练习说明(从站点复制粘贴):

这些不是完整的说明,只是我遇到问题的部分。

我想出了如何计算文本中字母的数量,但我不知道如何计算单词和句子。我试过用谷歌搜索并使用其他外部资源,但弹出的只是问题的答案,坦率地说,这感觉就像作弊。这是我的代码:

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>


int main (void)
{
    int letters = 0;
    string text = get_string("Text: ");
    int words = 0;

    for (int i = 0; i < strlen(text);i++)
    {
        if(isalpha(text[i]) != 0)
        {
        letters++;
        }
    }
    printf("Letters: %i\n", letters);
    


   for (int i = 0; i < strlen(text);i++)
   {
       if (isspace(text[i]) != 0)
       {
          if(isalpha (text[i] + 1) != 0) 
          {
              words++;
          }
       }
 
   }
   
   printf("Words: %i\n", words);
}

此代码计算出正确的字母数,但始终键入单词 : 0。我还没有完成句子部分。我可以帮忙吗?如果你告诉我答案,你能解释为什么是这个答案吗?

for (int i = 0; i < strlen(text);i++)
{
    if (isspace(text[i]) != 0)
    {
       if(isalpha (text[i] + 1) != 0) 
       {
           words++;
       }
    }
}

这里有些错误。你需要做的是意识到这个程序可以处于两种状态之一。您当前是否正在阅读一个单词。

bool reading_word = false; // Flag
int words = 0;

for(int i=0; i<strlen(text); i++) {
    if(isspace(text[i]) {
        reading_word = false;
    }
    else if(isalpha(text[i])) {
        if(!reading_word) {
            reading_word = true;
            words++;
        }
    }
}

另外,不要写if(isspace(text[i]) != 0)。它 returns 是一个布尔值,所以它基本上意味着要读取“if text[i] is a space”,所以只写 if(isspace(text[i]))

此外,在您的代码中 isalpha (text[i] + 1) 是完全错误的,没有任何意义。由于这是作业,所以我留给你找出原因。

对于句子,你可以使用这样的函数:

int isdelim(char c)
{
    return c == '.' || c == '!' || c == '?';
}

然后以与计算单词的循环类似的方式使用它。