C语言标准库中有一个字符串操作函数strstr,该函数实在s1中查找整个s2第1次出现的起始位置,并返回一个指向该位置的指针。如果s2并没有出现在s1的任何地方,函数将返回一个NULL指针。如果第二个函数是一个空字符串,函数就返回s1。
函数实现:http://blog.csdn.net/qq_34021920/article/details/76098237
今天我们再来实现一个strrstr函数,在s1中查找整个s2最后一次出现的位置。
直接上代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *my_strrstr(const char *s1, const char s2[])
{
assert(s1);
assert(s2);
char* last = NULL;
char* start = s1;
int j = 0;
if(*s2 == 0)
return 0;
while (*s1&&*s2)
{
start = s1;
while (*s1&&s2[j] && *s1 == s2[j])
{
s1++;
j++;
}
if (s2[j] == '\0')
{
last = start;
}
s1 = start + 1;
j = 0;
}
if (*s1 == '\0')
return last;
else
return NULL;
}
int main()
{
const char *arr = "abcdabcdef";
const char *arr2 = "cd";
char *ret = my_strrstr(arr, arr2);
printf("%s\n", ret);
system("pause");
return 0;
}
运行结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)