fixed implementation error; not all matches were found (e.g. xy in xxy)
there is no optimization, the book version is used thus the renamemaster
parent
8ebefb2974
commit
09fb685153
|
@ -1,21 +1,19 @@
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
#define MAXLINE 1000 /* maximum input line length */
|
#define MAXLINE 1000 /* maximum input line length */
|
||||||
|
|
||||||
int getln(char line[], int lim);
|
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 */
|
/* find: prints lines containing pattern, returns number of matching lines */
|
||||||
int find(char *pattern, char lineno_flag, char except_flag)
|
int find(char *pattern, char lineno_flag, char except_flag)
|
||||||
{
|
{
|
||||||
char line[MAXLINE];
|
char line[MAXLINE];
|
||||||
int found = 0;
|
int found = 0;
|
||||||
int slen = strlen(pattern);
|
|
||||||
long lineno;
|
long lineno;
|
||||||
|
|
||||||
for (lineno = 1; getln(line, MAXLINE) > 0; 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)
|
if (lineno_flag)
|
||||||
printf("%ld:", lineno);
|
printf("%ld:", lineno);
|
||||||
printf("%s", line);
|
printf("%s", line);
|
||||||
|
@ -36,15 +34,14 @@ int getln(char *s, int lim)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* strindex: return index of t in s, -1 if none */
|
/* 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;
|
int i, j, k;
|
||||||
|
for (i = 0; s[i]; i++) {
|
||||||
for (i = j = 0; s[i]; i++)
|
for (j=i, k=0; t[k] && s[j] == t[k]; j++, k++)
|
||||||
if (s[i] != t[j])
|
;
|
||||||
j = 0;
|
if (k > 0 && !t[k])
|
||||||
else if (++j == slen) { // found match
|
return i;
|
||||||
return i - slen + 1;
|
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
Loading…
Reference in New Issue