编写函数 strindex(s, t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1。
#include <stdio.h>
#define MAXLINE 1024
int getline(char line[], int max);
int strindexR(char s[], char t[]);
int main()
{
char s[MAXLINE];
char t[MAXLINE];
int n = 0;
printf("input a pattern:");
n = getline(t, MAXLINE);
t[n - 1] = '\0';
printf("now begin:\n");
while (getline(s, MAXLINE) > 0)
{
if ((n = strindexR(s, t)) >= 0)
printf("Found:%sPosition:%d\n", s, n);
}
}
int getline(char line[], int max)
{
char c;
int i = 0;
while (--max > 0 && (c = getchar()) != EOF && c != '\n')
line[i++] = c;
if (c == '\n')
line[i++] = c;
line[i] = '\0';
return i;
}
int strindexR(char s[], char t[])
{
int i, j, k, n;
n = -1;
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')
n = i;
}
return n;
}