问题描述
编写函数strrindex(s, t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1。 设计一个合适的主程序测试你编写的函数。字符串的长度不超过1000。
输入
输入数据有两行,第一行是字符串s,第二行是字符串t。
输出
如果字符串s中包含字符串t,则输出t在s中最右边出现的位置,否则输出-1。
输入样列
I am a student.
am
输出样例
2
输入样例
The Internet developers wanted to make a networking protocol that had serious longevity, so they had to define a large enough IP address space to last well beyond the foreseeable future.
the
输出样例
163
#include <stdio.h>
#include <string.h>
int strrindex(char s[],char t[])
{
int i,j,k;
int len=strlen(s);
for(i=len-1;i>=0;i--){
for(j=i,k=0;t[k]!=0 && s[j]==t[k];j++,k++){
if(k>0 && t[k]=='\0')
return i;
}
}
return -1;
}
int main()
{
char s[1010];
char t[1010];
gets(s),gets(t);
printf("%d\n",strrindex(s,t));
return 0;
}
#include <stdio.h>
#include <string.h>
int strrindex(char s[], char t[])
{
int i, j, k;
int lens = strlen(s),lent = strlen(t);
i = lens - 1;
j = lent - 1;
while(i >= 0){
if(s[i] == t[j]){
if(j == 0){
return i;
}
i --;
j --;
}else{
j = lent - 1;
i --;
}
}
return -1;
}
int main()
{
char s[1010];
char t[1010];
gets(s), gets(t);
printf("%d\n", strrindex(s, t));
return 0;
}
修改如下,供参考:
#include <stdio.h>
#include <string.h>
int strrindex(char s[],char t[])
{
int i,j,k;
int len=strlen(s);
for(i=len-1;i>=0;i--){
for(j=i,k=0;s[j]==t[k];j++,k++){//t[k]!=0 &&
if(t[k+1]=='\0') //if(k>0 && t[k]=='\0')
return i;
}
}
return -1;
}
int main()
{
char s[1010];
char t[1010];
gets(s),gets(t);
printf("%d\n",strrindex(s,t));
return 0;
}