#include <stdio.h>
#include <string.h>
int strrindex1(char s[],char t[]);
int strrindex2(char s[],char t[]);
/*
需求4-1:编写函数strrindex(s,t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1;
思路(仿p59):
*/
int main(){
printf("%d\n",strrindex1("abcdefyf","cde"));
printf("%d\n",strrindex2("abcdefyf","cde"));
return 0;
}
/*自解*/
int strrindex1(char s[],char t[]) {
int i, j, k;
for (i = 0; s[i] != '\0'; i++) {//遍历s
for (j = i,k = 0; t[k] != '\0' && s[j] == t[k]; j++,k++)//匹配遍历
;
if (k > 0 && t[k] == '\0')
return (j-1);
}
return -1;
}
/*
standard unswer(confuse):
执行效率更高
*/
int strrindex2(char s[],char t[]) {
int i, j, k;
for (i = strlen(s) - strlen(t); i >= 0; i--) {
for (j = i,k = 0; t[k] != '\0' && s[j] == t[k]; j++,k++)
;
if (k > 0 && t[k] == '\0')
return (j-1);
}
return -1;
}
输出:
4
4
--------------------------------
Process exited after 0.0302 seconds with return value 0
请按任意键继续. . .