Simple string Matching method

Source: Internet
Author: User
Tags first string strlen

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&GT;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<&lt '), 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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.