#include<stdio.h> #define MaxSize 255 typedef struct { char ch[MaxSize]; int length; }SString; void InitStr(SString &S) { S.ch[0]=' '; S.length=0; } void StrCreate(SString &S,char a[]) { int i=0,j=1; while(a[i]!=' ') { S.ch[j++]=a[i++]; } S.length=i; } int Index(SString S,SString T) //1.简单模式匹配 { int i,k,j; k=1;i=k;j=1; while(i<S.length && j<T.length) { if(S.ch[i]==T.ch[j]) { i++;j++; } else //匹配失败,主串模式串皆回退重新匹配 { k++; i=k; j=1; } } if(j>=T.length) return k; else return 0; } void get_next(SString T,int next[]) //模式串右移位数 { int i=1,j=0; next[1]=0; while(i<T.length) { if(j==0 || T.ch[i]==T.ch[j]) { i++;j++; next[i]=j; } else j=next[j]; } } int Index_KMP(SString S,SString T) //2.KMP算法 { int i=1,j=1; int next[255]; get_next(T,next); while(i<=S.length && j<=T.length) { if(j==0 || S.ch[i]==T.ch[j]) { i++;j++; } else j=next[j]; //模式串向后移动 } if(j>T.length) return i-T.length; else return 0; } void main() { SString S; InitStr(S); char a[]="abcdefg"; char b[]="bcd"; StrCreate(S,a); SString T; StrCreate(T,b); printf("The T is Num %d in S ",Index(S,T)); printf("The T is Num %d in S ",Index_KMP(S,T)); }