Idea: it is actually matching one by one. There are no highlights in the solution, and I don't want to say anything. Of course, you can also embed IsMatch into StrStr to reduce the overhead of function calling, but the readability may be reduced. 1. If the current character matches, the current character is returned. 2. If the current character does not match, skip one step forward. In fact, similar to the idea of A String Replace Problem, the core reference code is as follows:
bool IsMatch(const char *Str, const char *Pattern) { assert(Str && Pattern); while(*Pattern != '\0') { if(*Str++ != *Pattern++) { return false; } } return true; } char* StrStr(const char *Str, const char *Pattern) { assert(Str && Pattern); while(*Str != '\0') { if(IsMatch(Str, Pattern)) { return const_cast<char *>(Str); } else { ++Str; } } return NULL; }
Call the main function as usual:
# Include <stdio. h> # include <assert. h> int main () {const int MAX_N = 50; char Str [MAX_N]; char Pattern [MAX_N]; char * Ans = NULL; while (gets (Str) & gets (Pattern) {Ans = StrStr (Str, Pattern); if (Ans) {puts (Ans );} else {printf ("not a substring \ n ");}}
Return 1 ;}