#include
#include
#define MAXSIZE 20
char *String_Create()
{
char *s,ch;
int i=0;
s=(char *)malloc(sizeof(MAXSIZE));
ch=getchar();
while(ch!='\n')
{
*(s+i)=ch;
i++;
ch=getchar();
}
return s;
}
int String_Length(char *s)
{
int l=0;
while(*s!='\0')
{
l++;
s++;
}
return l;
}
int String_IndexKMP(char *d,char *s,int pos)
{
int i=pos,j=1,ld,ls;
ld=String_Length(d);
ls=String_Length(s);
int k=1,next[20],l=0;
next[1]=0;
while(k<ls)
{
if(l==0||(s+k)==(s+l))
{
++k;
++l;
if((s+k)!=(s+l))
next[k]=l;
else
next[k]=next[l];
}
else
l=next[l];
}
while(i<=ld&&j<=ls)
{
if(j==0||(ld+i)==(ls+j))
{
++i;
++j;
}
else
j=next[j];
}
if(j>ls)
return (i-ls);
else
return 0;
}
void String_Show(char *s)
{
while(putchar(*s++));
printf("\n");
}
int main()
{
char *str,*c;
int ans;
c=(char *)malloc(sizeof(MAXSIZE));
printf("請輸入主串:");
str=String_Create();
printf("請輸入子串:");
gets(c);
ans=String_IndexKMP(str,c,1);
printf("子串在主串中的位置為:%d",ans);
return 0;
}
http://blog.163.com/gene_lu/blog/static/640254212011111334214331/