String matching defines two nouns: a pattern string and a text string. Our task is to find the first occurrence of the pattern string in the text string, if we find the subscript to return the position, if no return-1 is found. This is actually a function of the C + + language:
extern Char *strstr (char *str1, const char *STR2);
For the explanation of this function:
STR1: Target str2: To find the object return value: If STR2 is a substring of str1, it returns the first occurrence of str2 at STR1, or null if STR2 is not a substring of str1. For example: Char str[]= "1234xyz"; char *str1=strstr (str, "cout"); str1 << Endl; display: 34xyz
The return value is a pointer to the position of the first occurrence of the pattern string in the text string.
Brute force algorithm for string lookup
First look at a topic on leetcode, implement this function int strStr (string haystack, string needle); Requires the return of the subscript value of the pattern string in the text string.
1. If the pattern string is NULL, return 0.2 directly. If the pattern string is longer than the text string, it must not be found, and returns-1.3. If present, the scope of the lookup can be limited to the 0~s.size ()-p.size () of the text string;
So the code implementation of the Brute force algorithm:
int StrStr (String haystack, string needle) {int i = 0;//pattern string is empty if (Needle.empty ()) {return 0;} The size of the text string is less than the pattern string if (Haystack.size () < Needle.size ()) {return-1;} Determine the range of lookups for (i = 0; I <= haystack.size ()-needle.size (); ++i) {int J = 0;for (j = 0; J < needle.size (); ++j) {if (Haystac K[I+J]! = Needle[j]) {break;}} Forif (j = = Needle.size ()) {return i;}} Forif (i = = Haystack.size ()-needle.size () + 1) {return-1;}}
From c++strstr to string matching algorithm