diff options
author | Martin Ashby <martin@ashbysoft.com> | 2022-11-14 21:21:31 +0000 |
---|---|---|
committer | Martin Ashby <martin@ashbysoft.com> | 2022-11-14 21:21:31 +0000 |
commit | bdc08b4f0507bc826c14737361f550ae0fc6b4c5 (patch) | |
tree | 87b98a856de94be0410c678ded374022637fe478 /ex4-1.c | |
parent | a4eda78b73cea22f36435f62ed52d071395bfc4f (diff) | |
download | learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.gz learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.bz2 learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.xz learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.zip |
Exercise 4-1
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 |