From 09fb6851538894cbcd459a24e588b439ff7a4f4a Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Sun, 23 Jul 2023 23:22:08 +0200 Subject: [PATCH] fixed implementation error; not all matches were found (e.g. xy in xxy) there is no optimization, the book version is used thus the rename --- .../04-find/{find-opt.c => find-book.c} | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) rename k&r/04-funcs-and-prog-struct/04-find/{find-opt.c => find-book.c} (67%) diff --git a/k&r/04-funcs-and-prog-struct/04-find/find-opt.c b/k&r/04-funcs-and-prog-struct/04-find/find-book.c similarity index 67% rename from k&r/04-funcs-and-prog-struct/04-find/find-opt.c rename to k&r/04-funcs-and-prog-struct/04-find/find-book.c index 047dae4..a251088 100644 --- a/k&r/04-funcs-and-prog-struct/04-find/find-opt.c +++ b/k&r/04-funcs-and-prog-struct/04-find/find-book.c @@ -1,21 +1,19 @@ #include -#include #define MAXLINE 1000 /* maximum input line length */ int getln(char line[], int lim); -int strindex(char source[], char searchfor[], int slen); +int strindex(char source[], char searchfor[]); /* find: prints lines containing pattern, returns number of matching lines */ int find(char *pattern, char lineno_flag, char except_flag) { char line[MAXLINE]; int found = 0; - int slen = strlen(pattern); long lineno; for (lineno = 1; getln(line, MAXLINE) > 0; lineno++) - if ((strindex(line, pattern, slen) >= 0) != except_flag) { + if ((strindex(line, pattern) >= 0) != except_flag) { if (lineno_flag) printf("%ld:", lineno); printf("%s", line); @@ -36,15 +34,14 @@ int getln(char *s, int lim) } /* strindex: return index of t in s, -1 if none */ -int strindex(char s[], char t[], int slen) +int strindex(char s[], char t[]) { - int i, j; - - for (i = j = 0; s[i]; i++) - if (s[i] != t[j]) - j = 0; - else if (++j == slen) { // found match - return i - slen + 1; - } + int i, j, k; + for (i = 0; s[i]; i++) { + for (j=i, k=0; t[k] && s[j] == t[k]; j++, k++) + ; + if (k > 0 && !t[k]) + return i; + } return -1; }