diff options
Diffstat (limited to 'ex4-1.c')
-rw-r--r-- | ex4-1.c | 53 |
1 files changed, 53 insertions, 0 deletions
@@ -0,0 +1,53 @@ +#include <stdio.h> +#include <stdbool.h> + +static int _strlen(char s[]) { + int i; + for (i=0; s[i] != '\0'; i++) {} + return i; +} + +/** + * returns the start index of the rightmost occurrence of t in s. + * or -1 if t does not appear in s + * + * strings must be null-terminated + */ +int strrindex(char s[], char t[]) { + int s_len = _strlen(s); + int t_len = _strlen(t); + char last_t = t[t_len-1]; + for (int i=(s_len-1); i>=0; i--) { + if (s[i] == last_t) { + int j = i; + int k = t_len-1; + bool full_match = true; + while (k >= 0) { + if (j < 0 || s[j] != t[k]) { + full_match = false; + break; + } + j--; + k--; + } + if (full_match) { + return j+1; + } + } + } + return -1; +} + +static void test(char s[], char t[]) { + printf("strrindex s = [%s] t = [%s] result = %d\n", s, t, strrindex(s, t)); +} + +int main(void) { + test("", ""); + test("x", ""); + test("x", "x"); + test("x", "xx"); + test("xox", "x"); + test("xox", "ox"); + test("xox", "xox"); +}
\ No newline at end of file |