Blob


1 /*
2 * Exercise 4-1. Write the function strrindex(s,t), which returns the position
3 * of the rightmost occurrence of t in s, or -1 if there is none.
4 */
6 #include <stdio.h>
7 #include <string.h>
8 #define MAXLINE 1000 /* maximum input line length */
10 int getlin(char line[], int max);
11 int strindex(char source[], char searchfor[]);
12 int strrindex(char s[], char t[]);
14 char pattern[] = "or"; /* pattern to search for */
16 /* find all lines matching pattern */
18 int main() {
19 char line[MAXLINE];
20 int found = 0;
21 int index = 0;
23 printf("pattern: %s\n", pattern);
24 while (getlin(line, MAXLINE) > 0)
25 if ((index = strrindex(line, pattern)) >= 0) {
26 printf("index: %d, %s", index, line);
27 found++;
28 }
29 return found;
30 }
32 /* getlin: get line into s, return length */
33 int getlin(char s[], int lim) {
34 int c, i;
35 i = 0;
36 while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
37 s[i++] = c;
38 if (c == '\n')
39 s[i++] = c;
40 s[i] = '\0';
41 return i;
42 }
44 /* strindex: return index of t in s, -1 if none */
45 int strindex(char s[], char t[]) {
46 int i, j, k;
48 for (i = 0; s[i] != '\0'; i++) {
49 for (j=i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++)
50 ;
51 if (k > 0 && t[k] == '\0')
52 return i;
53 }
54 return -1;
55 }
57 /* strrindex: return index of rightmost t in s, -1 if none */
58 int strrindex(char s[], char t[]) {
59 int i, j, k;
60 for (i = strlen(s)-1; s[i] != '\0'; i--) {
61 for (j=i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++)
62 ;
63 if (k > 0 && t[k] == '\0')
64 return i;
65 }
66 return -1;
67 }