Skip to main content
4 of 6
added 261 characters in body

Already there are great answers for C++. But in case of C, I would like to add one more point: instead of using two loops we can divide the tasks into functions.

/*compare two strings if they are same then return 0,
other wise return ASCII difference between characters.*/ 
int compare(char *s1, char *s2)
{
    for (; *s1 && *s2 && *s1 == *s2; s1++, s2++)
        ;
    return *s1 - *s2;
}
/* find/locate substring in string and returns a pointer points to
 the first character of the found substr in str otherwise a null pointer. */ 
char *mystrstr(char *str, char *substr)
{
    for (int i = 0; str[i] != '\0'; i++)
    {
        if (compare((str + i), substr) == 0)
        {
            return str + i;
        }
    }
    return NULL;
}