C language: customizes a function for searching strings, similar to strstr (), string. hstrstr in <string. h>.
// Customize a string to search for the standard library function strstr ()
# Include <stdio. h>
# Include <string. h>
Char * myStrstr (char * str1, char * str2 );
Int main ()
{
Char * str1 = "hello worl world ld ";
Char * str2 = "world ";
Puts (myStrstr (str1, str2 ));
Return 0;
}
Char * myStrstr (char * str1, char * str2)
{
Static int count = 0;
Const char * p = str2;
Char * pt;
While (* (str2 ++ ))
{
While (* (str1 ++ ))
{
// If the first character of str2 and str1 is the same, and then the second character is compared, count is accumulated.
If (* (str2-1) = * (str1-1 ))
{
Count ++;
Break;
}
// If the first character of str2 and str1 is different, traverse str1 until the end
Else if (* (str2-1 )! = * (Str1-1) & count <strlen (p ))
{
Continue;
}
// If the first few characters of str2 and str1 are the same, str2 starts from scratch.
Else
{
Str2 = str2-count;
Break;
}
}
If (* str2 = '\ 0' & count = strlen (p ))
Pt = str2-count; // locate the string, move the pointer to the first address of str2 and return
Else
Pt = NULL; // the string is not found and NULL is returned.
}
Return pt;
}