diff --git a/ch_04/exercise_04-01/compile.sh b/ch_04/exercise_04-01/compile.sh new file mode 100755 index 0000000..5593686 --- /dev/null +++ b/ch_04/exercise_04-01/compile.sh @@ -0,0 +1,5 @@ +#!/bin/bash + + + +gcc main.c kstrindex.c -I. -std=gnu99 -o a.out diff --git a/ch_04/exercise_04-01/kstrindex.c b/ch_04/exercise_04-01/kstrindex.c new file mode 100644 index 0000000..dd95488 --- /dev/null +++ b/ch_04/exercise_04-01/kstrindex.c @@ -0,0 +1,34 @@ +#include + +#include "kstrindex.h" + + +int KStrIndex_strindex(char s[], char t[]) +{ + // Defaults to negative + int result = -1; + int i = 0, k = 0; + int j = 0; + + for (i = 0; s[i] != '\0'; ++i) + { + for (j = i, k = 0; t[k] != '\0'; ++j, ++k) + { + if (s[j] != t[k]) + { + break; + } + } + + // Found starting index of t in s. As the look continues, + // there is a check to see if the string matches. This + // ensures that the right-most index is found. + if (k > 0 && t[k] == '\0') + { + result = i; + } + } + + + return result; +} diff --git a/ch_04/exercise_04-01/kstrindex.h b/ch_04/exercise_04-01/kstrindex.h new file mode 100644 index 0000000..e5d6bc4 --- /dev/null +++ b/ch_04/exercise_04-01/kstrindex.h @@ -0,0 +1,7 @@ +#include + + +// Returns the right most index of t found in s. +// Returns -1 if t is not found in s. +int KStrIndex_strindex(char s[], char t[]); + diff --git a/ch_04/exercise_04-01/main.c b/ch_04/exercise_04-01/main.c new file mode 100644 index 0000000..0ce0e21 --- /dev/null +++ b/ch_04/exercise_04-01/main.c @@ -0,0 +1,39 @@ +/* + * + * Exercise 4-1. Write the function strindex(s,t) which returns the position + * of the rightmost occurrence of t in s, or -1 if there is none + * + * Author: Kun Deng + */ + +#include +#include + +#include + +#define ARRAY_SIZE 99900000 + +int main() +{ + char s[] = "this is not the end, but it might as well be.The time is nigh. The end will befall all of us. The end.\0"; + char t[] = "end\0"; + + printf("Searching for string: %s\nIn: %s\n", t, s); + + const int index = KStrIndex_strindex(s, t); + + if (index == -1) + { + printf("String %s was not found\n", t); + + return -1; + } + + printf("String: %s\n", s); + printf("Sub String: %s\n", t); + printf("Index %d\n", index); + + return 0; +} + + diff --git a/ch_04/main_template.c b/ch_04/main_template.c new file mode 100644 index 0000000..bc72931 --- /dev/null +++ b/ch_04/main_template.c @@ -0,0 +1,14 @@ +/* + * + * Exercise 4- + * + * Author: Kun Deng + */ + + +int main() +{ + + + return 0; +}