summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Ashby <martin@ashbysoft.com>2022-11-14 21:21:31 +0000
committerMartin Ashby <martin@ashbysoft.com>2022-11-14 21:21:31 +0000
commitbdc08b4f0507bc826c14737361f550ae0fc6b4c5 (patch)
tree87b98a856de94be0410c678ded374022637fe478
parenta4eda78b73cea22f36435f62ed52d071395bfc4f (diff)
downloadlearn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.gz
learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.bz2
learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.tar.xz
learn-c-bdc08b4f0507bc826c14737361f550ae0fc6b4c5.zip
Exercise 4-1
-rw-r--r--ex4-1.c53
1 files changed, 53 insertions, 0 deletions
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 <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