练习4-1 编写函数strrindex(s,t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1。
#include <stdio.h>
#include <string.h>#define MAXLEN 100int strrindex(char s[], char t[]);int main()
{int c, i;char s[MAXLEN], t[MAXLEN];printf("please input str s, pattern t:\n");i = 0;while ((c = getchar()) != EOF && i < MAXLEN - 1)s[i++] = c;s[--i] = '\0'; //为了删掉getchar输入最后的回车符'\n'printf("please input pattern t:\n");i = 0;while ((c = getchar()) != EOF && i < MAXLEN - 1)t[i++] = c;t[--i] = '\0'; //为了删掉getchar输入最后的回车符'\n'printf("string index:%d\n", strrindex(s, t));return 0;
}int strrindex(char s[], char t[]) //从字符串s最后往前匹配
{int i, j, k;for (i = strlen(s) - 1; i > strlen(t) - 1 && i >= 0; i--){for (j = i, k = strlen(t) - 1; k >= 0 && s[j] == t[k]; j--, k--);if (k == -1){printf("%c\n", s[i - strlen(t) + 1]);return (i - strlen(t) + 1);}}return -1;
}