gpt4 book ai didi

计算 C 中用户输入字符串中的单词数

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:36 25 4
gpt4 key购买 nike

所以,我们在类里面得到了这个程序。 “用C写一个程序,统计用户输入的一句话的字数。”这是我能想出的,但单词的数量总是比正确的数字少一个。我的老师告诉每个人在打印之前将字数加 1。我认为它有一个错误,如果我们不输入任何单词,即按 Enter 而不是键入,我老师建议的程序仍然会将单词计数为 1 而不是 0。你知道有什么方法可以得到正确的单词吗计数而不只是在末尾加 1?代码:

我的代码(给了 1 小于正确):

#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
printf("enter the string\n");
gets(s);
for (i = 0;i<strlen(s);i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are: %d\n", count);
}

最佳答案

只是你在计算空格,如果用户以一堆空格结束字符串,这也是不正确的。尝试这样的事情:

#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
int foundLetter = False;
printf("enter the string\n");
gets(s);
for (i = 0;i<strlen(s);i++)
{
if (s[i] == ' ')
foundLetter = False;
else
{
if (foundLetter == False)
count++;
foundLetter = True;
}
}
printf("number of words in given string are: %d\n", count);
}

正如其他用户评论的那样,您的程序容易受到许多其他问题的影响,具体取决于输入的字符串。我发布的示例假设任何不是空格的东西都是一个字母,如果您找到至少一个字母,那就是一个单词。除了 bool 值,您还可以使用计数器来确保单词至少有一定长度。您还可以通过编写自己的正则表达式函数或使用现有函数来检查它不是数字或符号。正如其他人所说,您可以使用此程序做更多的事情,但我提供了一个示例来为您指明正确的方向。

关于计算 C 中用户输入字符串中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25746334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com