String matching is used in the actual development process, for example, most people like ctrl+f fast, whether in the code or in the text
Let's introduce a simple string matching method, which is an algorithm that most of us can easily think of.
The algorithm process is as follows:
For example, if we look for substring B in string A,
1. First obtain the length of a and B, len1 and len2, with two pointers or indexes P1 and P2 respectively, pointing to the first character of A and B.
2 when A[P1] and B[P2] are equal then P1 and P2 move backward by one character position
3. When A[p1]!=b[p2], P1 moves backwards one position, P2 points to the first string to be B
4. Repeat step 2,3 until the last character to P2 is matched, indicating that the match was successful.
5. The unsuccessful match condition is that if the number of remaining elements in a is less than the total number of elements not matched in B, the match is unsuccessful
The code is implemented as follows:
1 #include <iostream> 2 using namespace std;
3 4 bool Stringfun (char* orginstr,char* targetstr) 5 {6 int i,j;
7 i=0;
8 j=0;
9 int Len1=strlen (ORGINSTR);
Ten int Len2=strlen (TARGETSTR);
One if (LEN2>LEN1) return false; while ((LEN2-J) < (len1-i)) (Orginstr[i]==targetstr[j), {i++; 19
j + +; All else (i++, j=0) if (j== (LEN2)
), {+ = return true; The main () *strorgin,*strtarget () () () () () () () () () (); strorgin=new char[50]; strtarget=new Char
[50]; while (1) memset (strorgin, ' cout<< '), memset (strtarget, ' + '); ;"
Please input the Origin Str: ";
cin>>strorgin;
cout<< "Please input the targe Str:"; 49 cin>>strtarget;
-BOOL Flag;
Wuyi Flag=stringfun (Strorgin,strtarget);
if (flag) cout<< {"Find the child String" <<StrTarget<<endl; cout<< "Can not Find the child String" <<StrTarget<
<endl;
Delete[] Strorgin;
Strorgin=null;
Delete[] Strtarget;
Strtarget=null;
return; 68}
To run a screenshot: