Hi.
I'm doing K&R Exercise 5-4 (p107).
Write the function strend(s,t) , which returns 1 if the string t occurs at the end of the string s, and zero otherwise.
I figured the best way to do this was to...
- increment both pointers to the end
- count backwards through both strings whilst each char matches
- return 1 if we had finished counting to the beginning of the second string
So here is what I have...
int strend(const char *str1, const char *str2) {
int i = 0;
while (*str1++ != '\0');
while (*str2++ != '\0') {
i++;
}
i++;
while (*str2-- == *str1-- && i > 0) {
i--;
}
return (i == 0);
}
As you can see, I used a counter to tell when I had arrived at the beginning of the second string.
Is there any other loop I can use without a counter to tell when we have arrived at the start of the string (similar to looking for \0
for the end of a string)?
Thanks.
Update
Didn't think to use pointers - I'm still learning and forgetting a few things!
I came up with this...
int strend(const char *str1, const char *str2) {
char *start = str2;
while (*str1++ != '\0');
while (*str2++ != '\0');
while (*str2-- == *str1--) {
if (str2 == start) {
return 1;
}
}
return 0;
}