模拟实现strstr

来源:互联网 发布:数据修炼系统下载 编辑:程序博客网 时间:2024/06/05 22:52

strstr是查找子串的函数,从字符串str1中查找是否有字符串str2,如果有,从str1中的str2位置起,返回str1的指针,如果没有,返回null。

函数实现:

char *my_strstr(const char *str,const char *substr){    assert(str);    assert(substr);    char *cp = str;    if (*substr == '\0')        return NULL;    while (*cp)    {        char *s1 = cp;        char *s2 = substr;        while (*s1&&*s2&&*s1 == *s2)        {            s1++;            s2++;        }        if (*s2 == '\0')        {            return cp;        }        cp++;    }    return NULL;}

测试用例:

int main(){    char str1[] = "aabbcc";    char str2[] = "bc";    char *res = my_strstr(str1, str2);    printf("%s\n",res );    return 0;}

这里写图片描述