source code: #include<cstdio>#include<cstring>#include<iostream>using namespacestd;strings1,s2;intM,n,k (0), next[1001];//In the next array, the node number that the last one should jump to is stored when the match fails. intMain () {getline (CIN,S1); Getline (CIN,S2); M=s1.size (); N=s2.size (); next[0]=0;//before the first character, there are no comparable characters. for(intA=1; a<n;a++)//in C + +, strings actually exist in the form of an array of characters beginning with 0. { while(k>0&&s2[a]!=S2[k]) k=next[k-1];//after the match fails, a jump is made. if(s2[a]==S2[k]) k++; Next[a]=K; } k=0; for(intA=0; a<m;a++) { while(k>0&&S1[A]!=S2[K])//in the same vein. k=next[k-1]; if(s1[a]==S2[k]) k++; if(k==n)//The same length, matching success, output position. printf"%d", a-n+2); } return 0;}
String Matching--KMP algorithm (c + +)