The original test is incorrect, as indicated in other answers.
Here is a slightly smaller and potentially more efficient version:
int string_ends_with(const char *str1, const char *str2) {
const char *p1 = str1;
const char *p2 = str2;
while (*p1) p1++;
while (*p2) p2++;
while (p2 != str2) {
if (p1 == str1 || *--p1 != *--p2)
return 0;
}
return 1;
}
Note that your test function mainshould output something and do more tests:
void test(const char *a, const char *b) {
printf("\"%s\" ends with \"%s\": %s\n",
a, b, string_ends_with(a, b) ? "yes" : "no");
}
int main(void) {
char str[] = "banana";
char str1[] = "ana";
test(str, str1);
test(str1, str);
test(str, str);
test(str, "");
test("", str);
test("", "");
return 0;
}
source
share