C language simulation realizes strstr() of standard library function

strstr()

The strstr(str1,str2) function is used to determine whether the string str2 is a substring of str1. If so, the function returns the address of the first occurrence of str2 in str1; otherwise, it returns NULL.

char* my_strstr(const char* dest, const char* src)
{
    char * str1 = dest;
    char * str2 = src;
    char * p = (char *)dest;
    while (*p)
    {
        str1 = p;
        while (*str1 == *str2)
        {
            str1++;
            str2++;
        }
        if (!*str2)
        {
            return (char *)src;
        }
        str2 = (char*)src;
        p++;
    }
    return NULL;
}

int main()
{
    char a[20] = "aabccdef";
    char b[10] = "cde";
    printf("%s\n", my_strstr(a, b));
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325594575&siteId=291194637