#include <string.h>
#include <stdio.h>
const char* rstrstr (const char* haystack, const char* needle)
{
int needle_length = strlen(needle);
const char * haystack_end = haystack + strlen(haystack) - needle_length;
const char * p;
int i;
for(p = haystack_end; p >= haystack; --p)
{
for(i = 0; i < needle_length; ++i) {
if(p[i] != needle[i])
goto next;
}
return p;
next:;
}
return 0;
}
#define NTESTS 4
struct test {
const char * haystack;
const char * needle;
int expect;
} tests[NTESTS] = {
{
/* 345678901234567890 */
"monkey see monkey do",
"monkey",
11,
},
{
"many a mickle makes a muckle",
"mockl",
0,
},
{
/* 345678901234567890 */
"monster monkey monty",
"mon",
15,
},
{
/* 345678901234567890 */
"abcdefghiabcjibabc",
"abc",
15,
}
};
int main ()
{
int i;
for (i = 0; i < NTESTS; i++) {
const char * result;
printf ("test %d\n", i);
result = rstrstr (tests[i].haystack, tests[i].needle);
if (tests[i].expect == 0 && result == 0) {
printf ("OK\n");
continue;
} else {
printf ("%d %d\n", result - tests[i].haystack, tests[i].expect);
if (result - tests[i].haystack == tests[i].expect) {
printf ("OK\n");
continue;
}
}
printf ("failed\n");
}
return 0;
}