我的 C 代码没有正确计算单词和句子,而是计算字符

My C code is not counting properly word and sentences, but counting char

我正在编写一个 C 程序来计算字母、单词和句子的数量。但是 if 计算单词和句子的条件不检查空字符。任何人都可以帮助我:我做错了什么?

但是,如果计算字符数的条件是检查空字符。

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

int main (void)
{
    string text = get_string("text: ");
    int p=0,q=0,r,j=0,k=0;
    {
        printf("Your Text is : %s\n", text);
    }
    for(p=0,r=strlen(text); p<r; p++)
    {
        // for counting Letters.
        if (text[p]!= ' ' && text[p]!= '[=10=]' && text[p]!='-' && text[p]!='_' && text[p]!= '.')
        {
            q++;
        }
        // for counting Words.
        else if (text[p]==' ' || text[p]== '-' || text[p]== '[=10=]'  || text[p]=='_')
        {
            j++;
        }
        // for counting Sentences.
        else if (text[p]== '.' || text[p]== '!' || text[p]== '[=10=]')
        {
            k++;
        }
    }
    printf("no.of chars is %i\n",q);
    printf("no.of words is %i\n",j);
    printf("no.of sentences is %i\n",k);
}

包含用于获取字符串输入的 cs50 库

我猜你希望任何文本都是一个句子,但它永远不会被你的代码计算在内,因为你的代码永远不会进入对空字符的分析,只要它永远不会成为字符串的一部分。

C 字符串只是以空字符 (‘\0’) 结尾的字符数组。 此空字符指示字符串的结尾。 字符串总是用双引号括起来。然而,字符在 C 中用单引号括起来。

这意味着您的字符串以 null 结尾,即结尾之前的所有内容都是字符串主体,而不是 NULL 本身。

您可以按以下方式简单地更改您的代码:

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

int main (void)
{
    string text = get_string("text: ");
    int p=0,q=0,r,j=0,k=0;
    {
        printf("Your Text is : %s\n", text);
    }
    for(p=0,r=strlen(text); p<r; p++)
    {
        // for counting Letters.
        if (text[p]!= ' ' && text[p]!='-' && text[p]!='_' && text[p]!= '.')
        {
            q++;
        }
        // for counting Words.
        else if (text[p]==' ' || text[p]== '-' ||  text[p]=='_')
        {
            j++;
        }
        // for counting Sentences.
        else if (text[p]== '.' || text[p]== '!' || text[p]== '[=10=]')
        {
            k++;
        }
    }
        if ( q>0 && text[strlen(text)-1]!='.' && text[strlen(text)-1]!='!')
            { 
              j++;
              k++;
            }
        printf("no.of chars is %i\n",q);
        printf("no.of words is %i\n",j);
        printf("no.of sentences is %i\n",k);

}

更改背后的逻辑如下:

当您在字符串正文中查看单个字符时,您不需要检查空值。那是因为正如我已经提到的无用。 解析整个字符串后,您需要做的就是确保至少有一个字符 (i>0),然后按照到达字符串末尾的逻辑,您会自动到达单词的末尾和句子。