求一个用C或者C++写反向查找字符串的函数

比如在int rfind(const char*source ,const char* match),在字符串source中从右到左查找字符串match,找不到返回-1,找到返回match在source中的位置,如:source为“1230123”,match为“123”,则返回4

这里写了一种方法,是先找到最后一个指针,反向查找。你也可以先把字符串反转,再来查找,算法不一样,结果相同。不懂再问我。

#include<stdio.h>
int rfind(const char*source ,const char* match);
void main()
{
/*char *sourcetest = "1230123";
char *matchtest = "123";
printf("查找的最后结果是:\n");
printf("%d",rfind(sourcetest,matchtest));
getch();*/
char *source1;
char *match1;
printf("请输入原字符:\n");
scanf("%s",source1);
printf("请输入match字符串:\n");
scanf("%s",match1);
printf("查找的最后结果是:\n");
printf("%d\n",rfind(source1,match1));
getch();

}
int rfind(const char*source ,const char* match)
{
char *p;
int n = 0;
p = source;
/*让指针p指向最后一个位置*/
for(; *p != '\0';p++)
{
n++;
}
for(;n>0;n--)
{
if(*p == *match)
{
return (strlen(p)+1);
}
p--;
}
return -1;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-05-14

精简后:

int rfind(const char*source ,const char* match)
{
    // for(int i=strlen(source);i>=0;i--) 
     for(int i=strlen(source)-strlen(match)-1;i>=0;i--) //原来的代码有点小问题。
     {
           if(source[i]==match[0] && strncmp(source+i, match, strlen(match))==0) return i;
     }
      return -1;           
}

本回答被网友采纳
第2个回答  2013-03-26
既然本来就有从左到右查找的函数strstr,从右到左不就可以利用这个函数做文章嘛
当然自己写个也不麻烦
第一种思想就是:你可以先把字符串和匹配字符串翻转,利用strstr函数,根据源字符串的长度计算出位置
第二种思想就是:不翻转,利用strstr循环查找,找到最后一个位置,返回。
第三种思想就是:不利用strstr字符串查找函数,自己匹配编写
for(i=s_len-1;i>=0;i--)
for(j=m_len-1;j>=0;j--)
{
依次匹配

}
我只说思想,代码自己实现看看
第3个回答  2013-03-27
这个很简单,直接调用find函数,找到最后一个匹配的就可以了,或者倒序匹配,《C和指针》上有,自己写吧,自己想办法解决问题!
第4个回答  2013-03-26
int rfind(const char*source ,const char* match)
{
int i=0;
int l=strlen(match);
char str[1000]={0};
for(i=0;i<strlen(source);i++)
{
strcpy(str,source,l);
if(strcmp(str,match)==0)
return i;
}
return -1;
}