Reputation: 109
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. 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:
Enter a string:
I am happy.
longWordLength(): 5
but for a test case like Test Case 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. Seeking anyone's kind guidance on my issue as I really can't seem to figure out the issue. Thank you in advanced.
Upvotes: 3
Views: 258
Reputation: 144695
The problem is in while (*s++ != '\0') {
: you increment the string pointer before testing the character it points to. 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.
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;
}
Upvotes: 2