diff options
Diffstat (limited to 'four/grep.c')
-rw-r--r-- | four/grep.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/four/grep.c b/four/grep.c new file mode 100644 index 0000000..7e6b4db --- /dev/null +++ b/four/grep.c @@ -0,0 +1,58 @@ +#include <stdio.h> +#include <string.h> + +#define MAXLINE 1024 + +int +get_line(char s[], int lim) +{ + int c, i; + i = 0; + while (--lim > 0 && (c = getchar()) != EOF && c != '\n') { + s[i++] = c; + } + if (c == '\n') { + s[i++] = c; + } + s[i] = '\0'; + return i; +} + +int strindex(char s[], char t[]) +{ + int i, j, k; + for (i = 0; s[i] != '\0'; ++i) { + for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; ++j, ++k); + if (k > 0 && t[k] == '\0') { + return i; + } + } + return -1; +} + +int strrindex(char s[], char t[]) +{ + int i, j, k; + for (i = strlen(s) - 1; i > 0; --i) { + for (j = i, k = strlen(t) - 1; k > 0 && s[j] == t[k]; --j, --k); + if (t[k] == t[0]) { + return i; + } + } + return -1; +} + +int +main() +{ + char line[MAXLINE]; + char pattern[] = "ould"; + int found = 0; + while (get_line(line, MAXLINE)) { + if (strrindex(line, pattern) >= 0) { + printf("%s", line); + ++found; + } + } + return found; +} |