/* Exercise 4-1 of _The C Programming Language_: "write the function strrindex(s,t), which returns the position of the rightmost occurence of t in s, or -1 if there is none. 12/03/01. */ #include #define MAXLINE 1000 #define DEBUG 1 /* strrindex: returns index of rightmost occurence of t in s, -1 if none. searches from back to front of string. */ int strrindex(char s[], char t[], int n) { int i, j, k; if (DEBUG) { printf(" DEBUG: in strrindex, n = %i \n", n); printf(" DEBUG: s = %s \n", s); printf(" DEBUG: t = %s \n", t); } for(i = n; s[i] != '\0'; i--) { if (DEBUG) printf(" DEBUG: i loop, i = %i, s[i] = '%c' \n", i, s[i]); for(j = i, k = 0; (t[k] != '\0') && (s[j]==t[k]); j++, k++) if (k < n && t[k] =='\0') return i; } return -1; } /* getline: lifted straight from the book. gets line into s, returns length. */ int getline(char s[], int lim) { int c, i; i = 0; while((--lim > 0) && ((c=getchar()) != EOF) && (c != '\n')) s[i++] = c; if (c == '\n') s[i++] = c; s[i] = '\0'; return i; } main() { char pattern[] = "mus"; char line[MAXLINE]; int found = 0; int n, m; n = getline(line, MAXLINE); if (DEBUG) printf(" DEBUG: input line = '%s' with %i chars. \n", line, n ); m = strrindex(line, pattern, n); if (m >= 0) printf("'mus' found in %s at %i\n", line, m); }