Ideas:
1. If the last character of the string is '\ 0', it can be used as a critical condition.
2. When * Str! = '\ 0', judge whether * P is equal to * q. If it is equal, move two pointers. If the last * q pointer reaches the boundary, the entire match is successful, return res directly. Otherwise, move the primary string pointer.
# Include <iostream>
Char * mystrstr (char * STR, char * substr ){
While (* Str! = '\ 0 '){
Char * P = STR;
Char * q = substr;
Char * res = NULL;
If (* P = * q ){
Res = P;
While (* Q! = '\ 0' & * P = * q ){
P ++;
Q ++;
}
If (* q = '\ 0 ')
Return res;
}
STR ++;
}
Returnnull;
}
Int main (INT argc, constchar * argv [])
{
Char * S1 = "abcdefghijklmn ";
Char * S2 = "BCD ";
// Search for string 2 in string S1. If the return position is found, otherwise null is returned.
Char * res = mystrstr (S1, S2 );
If (res! = NULL ){
Printf ("% s", Res );
} Else {
Printf ("not ");
}
Printf ("\ n ");
Return0;
}
Result:
Implementation of the C-Series function prototype-strstr (char * STR, char * substr)