自定义函数实现strstr字符串查找函数
自定义函数实现strstr字符串查找函数
编译环境VS2019
#include <stdio.h>
#include <assert.h>
char* my_strstr(const char* p1, const char* p2)
{
//断言
assert(p1 && p2);
char* s1 = NULL;
char* s2 = NULL;
char* cur = (char*)p1;
if (*p2 == '\0')
return (char*)p1;
while (*cur)
{
s1 = cur;
s2 = (char*)p2;
while (*s1 && *s2 && (*s1 == *s2))
{
s1++;
s2++;
}
//找到子串,返回开始相同的字符串地址
if (*s2 == '\0')
{
return cur;
}
//当*s1=='\0',s2字符串没找完时,返回空地址串
if (*s1 == '\0')
{
return NULL;
}
cur++;
}
return NULL;
}