Exercise 4-1 (Rightmost pattern)

Chapter_4     pattern atof     Exercise_4-2







Exercise 4-1     K&R, p. 71


Exercise 4-1. Write the function strrindex(s,t), which returns the position of the rightmost occurrence of t in the string s, or -1 if there is none.




patternr.c     K&R, p. 69         download


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

#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 last index or -1 if not found:
int strrindex(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 (strrindex(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 last index or t[] in s[] or -1 if not found
int strrindex(char s[], char t[])
{
int i, j, k;
int len_t = strlen(t);

for (i = strlen(s)-1; i >= 0; i--)
{
for (j = i, k = len_t-1; k >= 0 && s[j] == t[k]; j--, k--)
{}
if (k < 0)
{return i-len_t+1;} // found, return last index
} // i-(len_t-1)

return -1; // not found
}
/*
gcc patternr.c -o patternr
./patternr < 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!
*/





Note:  See pattern for the file Khayam.txt.









Chapter_4     pattern BACK_TO_TOP atof     Exercise_4-2



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo