ch4-pattern

Chapter_4 Exercise_4-1







CONTENTS:     Khayam.txt     pattern.c




Khayam.txt     K&R, p. 68         download


Ah Love! could you and I with Fate conspire
To grasp this sorry Scheme of Things entire,
Would not we shatter it to bits -- and then
Re-mould it nearer to the Heart's Desire!





pattern.c     K&R, p. 69         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define MAXLINE 1000

int main(); // can be declared before definition
int getLine(char line[], int max); // getline() is declared by stdio.h
// searchfor[] in source[], return first index or -1 if not found:
int strindex(char source[], char searchfor[]);

int main()
{
char line[MAXLINE];
int found = 0, len;
char pattern[] = "ould";
// find all lines matching pattern:
while ((len = getLine(line, MAXLINE)) > 0)
{
if (strindex(line, pattern) >= 0)
{
printf("%s", line);
if (line[len-1] != '\n')
{putchar('\n');} // line may not end with '\n'
found++;
}
}

return found;
}
// get line into s[], return length
int getLine(char s[], int lim)
{
int c = EOF, i = 0; // initialize

while(--lim > 0 && (c = getchar()) != EOF && c != '\n')
{s[i++] = c;}
if (c == '\n') {s[i++] = c;} // s[i++] = '\n';
s[i] = '\0'; // properly end string

return i; // line length
}
// return first index or t[] in s[] or -1 if not found
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;} // found, return first index
}

return -1; // not found
}
/*
gcc pattern.c -o pattern
./pattern < Khayam.txt
// Omar Khayam, Rubaiyat (Edward Fitzgerald):
Ah Love! could you and I with Fate conspire
Would not we shatter it to bits -- and then
Re-mould it nearer to the Heart's Desire!
*/









Chapter_4 BACK_TO_TOP Exercise_4-1



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo