summaryrefslogtreecommitdiff
path: root/ex4-1.c
blob: ba3660e9339badbb4ae845ba8888364af72c9fc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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");
}