Page 71

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

#include <stdio.h>
#define MAXLINE 1000

int get_line(char line[], int max);
int strrindex(char source[], char searchfor[]);

char pattern[] = "ould";

int main()
{
	char line[MAXLINE];
	int idx;

	while (get_line(line, MAXLINE) > 0) {
		idx = strrindex(line, pattern);
		if (idx >= 0) {
			printf("%s%d", line, idx);
		}
	}
}

int get_line(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;
}

int strrindex(char s[], char t[])
{
	int i, j;
	int idx = -1;
	for (i = 0; s[i] != '\0'; i++) {
		for (j = 0; s[i + j] == t[j] && t[j] != '\0'; j++)
			;
		if (t[j] == '\0') {
			idx = i;
		}
	}
	return idx;
}