// 用next求kmp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void get_next(char T[],int next[]){
//求模式串T的next函数值并存入数组next
int i=1;next[1]=0;
int j=0;
int n;
n=strlen(T);
while(i<n){
if(j==0 || T[i]==T[j]) {++i;++j;next[i]=j;}
else j=next[j];
}
}
int Index_KMP(char S[],char T[],int pos,int next[]){
//利用模式串T的next函数求T在主串中第pos个字符之后的位置的
//KMP算法.其中,T非空,1<=pos<=StrLength(S).
int i=pos;
int j=1;
int m,n;
m=strlen(S);
n=strlen(T);
while(i<=m && j<=n){
if(j==0 || S[i]==T[j]){++i;++j;}//继续比较后续字符
else j=next[j];
}
if(j>n) return i-n;//匹配成功
else return 0;
}
int main(int argc, char* argv[])
{
char CS[100],char CT[100];
int data,data1,ne[100];
cout<<"请输入主串"<<endl;
cin>>CS;
cout<<"请输入子串"<<endl;
cin>>CT;
cout<<"请输入主串中从第pos个字符开始匹配的"<<endl;
cin>>data;
get_next(CT,ne);
data1=Index_KMP(CS,CT,data,ne);
cout<<data1<<endl;
return 0;
}