Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created November 23, 2009 06:47
Show Gist options
  • Save shaobin0604/240932 to your computer and use it in GitHub Desktop.
Save shaobin0604/240932 to your computer and use it in GitHub Desktop.
/*
* Exercise 4-1. Write the function strindex(s,t) which returns the position
* of the rightmost occurrence of t in s, or -1 if there is none.
*/
#include <stdio.h>
#include <string.h>
int strindex(char s[], char t[]);
int main(void)
{
char* s[] = {"abcdefgabcdefg", "adefg"};
char* t[] = {"def", "acg"};
int r[] = {10, -1};
size_t len = sizeof(s)/sizeof(s[0]);
int i = 0;
while (i < len)
{
if (r[i] == strindex(s[i], t[i]))
printf("assert success.\n");
else
printf("assert fail.\n");
i++;
}
return 0;
}
int strindex(char s[], char t[])
{
int slen = strlen(s);
int tlen = strlen(t);
int i = slen - 1, j, k;
while (i >= 0)
{
j = tlen - 1;
k = i;
while (k >= 0 && j >= 0 && s[k--] == t[j--])
;
if (j < 0)
return k + 1;
i--;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment