问题:我似乎无法让我的测试用例 4 工作。
问题:
写一个C函数,接受一个英文句子作为参数,返回句子中最长单词的长度。例如,如果句子是“I am Tim.”,则返回第 3 句中最长单词“time”的长度。
测试用例 1:
Enter a string: I am lee.
longWordLength(): 3
测试用例 2:
Enter a string: There are two disciples in the class.
longWordLength(): 9
测试用例 3:
Enter a string: Good night!
longWordLength(): 5
测试用例 4:
Enter a string: Jovial
longWordLength(): 6
这是我目前的代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int longWordLength(char *s);
int main()
{
char str[80], *p;
printf("Enter a string: \n");
fgets(str, 80, stdin);
if (p=strchr(str,'\n')) *p = '\0';
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(char *s)
{
int i, count, max;
max = 0;
count = 0;
while( *(s) != '\0' )
{
if ( *(s) != '\0' && *(s) != ' ' && *(s) != '.' )
{
count++;
printf("current count is %d\n", count);
}
else
{
if(count>max)
{
max = count;
printf("There is a new max! It is %d\n", max);
count = 0;
}
count = 0;
printf("count is resetted!\n");
}
s++;
printf("reach the end of the while loop\n");
}
printf("current max outside while loop is: %d\n", max);
printf("exited\n");
return max;
}
最佳答案
问题:
当关键字位于行尾时,您的代码将不起作用。
那是因为您的 max
在该 while 循环内更新,并且 while 循环在找到空字符时终止。由于空字符总是附加到输入字符串的末尾,因此字符串中的最后一个单词不会影响输出。在这种边缘情况下,循环不会提供在最终迭代中执行该 else
block 的机会。
事实上,您的代码只会通过测试用例 2,因为所有其他用例都包含输入字符串末尾的关键字。
解决方案:
即使您纠正了这一点,如果句子中包含句点以外的标点符号,您的代码仍可能会失败。
例如:“测试用例!”
新代码将计算“Case!”作为长度为 5 的单词,大于“Test”或“Case”的长度,并给出错误答案。
你可以看看一些图书馆functions C 必须提供,以帮助您通过所有边缘情况。
如果您需要更多帮助,我已对您的代码进行了必要的修改:
while( *(s) != '\0' )
{
// if ( *(s) != '\0' && *(s) != ' ' && *(s) != '.' )
// Why check the null character again?
// Spaces and period will not be the only punctuation marks
// You can check for all punctuation marks using ispunct() from <ctype.h>
if (!isspace(*s) && !ispunct(*s))
{
count++;
printf("current count is %d\n", count);
// You can update max here
if(count > max)
{
max = count;
printf("There is a new max! It is %d\n", max);
}
}
/*
Now you can eliminate this block of code
else
{
if(count>max)
{
max = count;
printf("There is a new max! It is %d\n", max);
count = 0;
}
count = 0;
printf("count is resetted!\n");
}
*/
// You can reset count after all that
else
{
count = 0;
printf("count is resetted!\n");
}
s++;
printf("reach the end of the while loop\n");
}
代码假设输入的是正确的英语句子。
P. S. This answer earned me the 1K reputation :)
关于c - 查找字符串中最长单词的长度。 C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361374/