[ create a new paste ] login | about

Link: http://codepad.org/KzryjtRE    [ raw code | output | fork ]

kinopiko - C, pasted on Oct 28:
#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;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
test 0
11 11
OK
test 1
OK
test 2
15 15
OK
test 3
15 15
OK


Create a new paste based on this one


Comments: