首页 > 代码库 > 字符串匹配之朴素匹配

字符串匹配之朴素匹配

 1 # include<iostream> 2 # include<cstdio> 3 # include<string> 4 using namespace std; 5 int index(char *a,char *b) 6 { 7     int n=0;//父串偏移量,初始为0 8     while(a[n]!=\0) 9     {10         int m = n;11         int k; //子串偏移量12         for(k = 0; b[k]!=\0; k++)13         {14             if(a[m++]!=b[k]) //不匹配,马上停止15             {16                 break;17             }18         }19         if(b[k]==\0)//匹配成功20         {21             return n;22         }23         n++;//父串,开始移动24     }25     return -1;26 }27 int main()28 {29     char *a = "abcdef";30     char *b = "cdef";31     cout<<index(a,b)<<endl;32 }
View Code

 

字符串匹配之朴素匹配