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



我正在制作一个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 : %sn", text);
}
for(p=0,r=strlen(text); p<r; p++)
{
// for counting Letters.
if (text[p]!= ' ' && text[p]!= '' && text[p]!='-' && text[p]!='_' && text[p]!= '.')
{
q++;
}
// for counting Words.
else if (text[p]==' ' || text[p]== '-' || text[p]== ''  || text[p]=='_')
{
j++;
}
// for counting Sentences.
else if (text[p]== '.' || text[p]== '!' || text[p]== '')
{
k++;
}
}
printf("no.of chars is %in",q);
printf("no.of words is %in",j);
printf("no.of sentences is %in",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 : %sn", 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]== '')
{
k++;
}
}
if ( q>0 && text[strlen(text)-1]!='.' && text[strlen(text)-1]!='!')
{ 
j++;
k++;
}
printf("no.of chars is %in",q);
printf("no.of words is %in",j);
printf("no.of sentences is %in",k);
}

更改背后的逻辑如下:

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

最新更新