请用标准C语言实现下列标准库函数,设计中不得使用其他库函数。
char *strstr(char *str1,char *str2);
char *strstr(char *str1,char *str2);
在字符串str1中,寻找字串str2,若找到返回找到的位置,否则返回NULL。
#include <iostream>
#include <cassert>
using namespace std;
const char* StrStr(const char *str1, const char *str2)
{
assert(NULL != str1 && NULL != str2);
while(*str1 != '\0')
{
const char *p = str1;
const char *q = str2;
const char *res = NULL;
if(*p == *q)
{
res = p;
while(*p && *q && *p++ == *q++)
;
if(*q == '\0')
return res;
}
str1++;
}
return NULL;
}
int main()
{
const char *str1 = "wangyang";
const char *str2 = "ang";
const char *res = StrStr(str1, str2);
if(res != NULL)
cout<<res<<endl;
else
cout<<"NOT"<<endl;
system("pause");
}