[英]Writing a C function to take in an english sentence as parameter and return the longest length word in the sentence
I have an assignment that requires me to write a function to take in an array containing an English sentence and return the length of the longest word in that sentence.我有一个作业要求我编写一个 function 来接收一个包含英语句子的数组并返回该句子中最长单词的长度。 This is the code I have so far:这是我到目前为止的代码:
int longWordLength(char *s); // Function prototype
int main() {
char str[80], *p;
printf("Enter a string: \n");
fgets(str, 80, stdin);
if (p = strchr(str,'\n'))
*p = '\0'; //converts newline to null
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(char *s) {
int count = 0, max = 0;
while (*s++ != '\0') {
if ((*s >= 'a' && *s <= 'z') || (*s >= 'A'&& *s <= 'Z')) {
count++;
} else {
if (count > max) {
max = count;
count = 0;
} else
count = 0; // word is not the longest
}
}
return max;
}
I have tried for a long time to diagnose the issue but to no avail.我已经尝试了很长时间来诊断问题,但无济于事。
This works with certain test case like:这适用于某些测试用例,例如:
Test Case 1:测试用例 1:
Enter a string:
I am happy.
longWordLength(): 5
but for a test case like Test Case 4:但是对于像测试用例 4 这样的测试用例:
Enter a string:
Hello
longWordLength(): 4 <- it prints 4 instead of 5.
I am not allowed to use any library other than the <string.h>
as it is for my school assignment.我不允许使用除<string.h>
之外的任何库,因为它用于我的学校作业。 Seeking anyone's kind guidance on my issue as I really can't seem to figure out the issue.在我的问题上寻求任何人的善意指导,因为我似乎真的无法弄清楚这个问题。 Thank you in advanced.提前谢谢你。
The problem is in while (*s++ != '\0') {
: you increment the string pointer before testing the character it points to.问题出在while (*s++ != '\0') {
:在测试它指向的字符之前增加字符串指针。 Just change to code to:只需将代码更改为:
for (; *s != '\0'; s++) {
...
Note however that the last word will not be tested the maximum length if it is not followed by some separator such as a space or a newline, which you would have stripped.但是请注意,如果最后一个单词后面没有一些分隔符,例如空格或换行符,则不会测试其最大长度,您将删除这些分隔符。
Note that stripping the trailing newline is not required for longWordLength()
to determine the correct count.请注意, longWordLength()
不需要去除尾随换行符来确定正确的计数。
Here is a modified version:这是修改后的版本:
#include <stdio.h>
int longWordLength(const char *s); // Function prototype
int main() {
char str[80];
printf("Enter a string: \n");
if (!fgets(str, sizeof str, stdin))
return 1;
// no need to strip the newline for this test:
printf("longWordLength(): %d\n", longWordLength(str));
return 0;
}
int longWordLength(const char *s) {
int count = 0, max = 0;
for (;; s++) {
if ((*s >= 'a' && *s <= 'z') || (*s >= 'A'&& *s <= 'Z')) {
count++;
} else {
if (count > max) {
max = count;
}
if (*s == '\0')
break;
count = 0; // reset the counter for the next word
}
}
return max;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.