From bdc08b4f0507bc826c14737361f550ae0fc6b4c5 Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Mon, 14 Nov 2022 21:21:31 +0000 Subject: Exercise 4-1 --- ex4-1.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 ex4-1.c (limited to 'ex4-1.c') diff --git a/ex4-1.c b/ex4-1.c new file mode 100644 index 0000000..ba3660e --- /dev/null +++ b/ex4-1.c @@ -0,0 +1,53 @@ +#include +#include + +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 -- cgit v1.2.3-ZIG