下面是我的代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int next[1001];//这个是next数组
//函数声明
void GetNext(char str[]);
int KMP(char str[],char temp[]);
int main()
{
int i = 0;
char str[1001];//这个是主字符串
char temp[1001];//这个是用来匹配的字符串
int length = 0;//这个是主字符串的长度。
int result = -1;
printf("请输入第一个字符串\n");
gets(str);//在vs中用scanf_s();
printf("请输入第二个字符串\n");
gets(temp);//在vs中用scanf_s();
GetNext(str);//建立next数组
result = KMP(str,temp);//这个是获取结果
printf("\n");
if (result <= 0) {
printf("没有找到匹配的字符串");
}
else {
printf("结果在主字符串的位置为 %d",result+1);
}
system("pause");
return 0;
}
void GetNext(char str[])//next数组的建立,这个是关键
{
int i=0,j = -1;
int length1 = strlen(str);
next[0] = -1;
while (i < length1) {
if ( j== -1 || str[j] == str[i]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
int KMP(char str[],char temp[])//这个是查找
{
int i = 0;//这个是主字符串的位置
int j = 0;//这个是子字符串的位置
int length1 = strlen(str);
int length2 = strlen(temp);
while (i<length1&&j<length2)
{
if (j==-1||str[i] == temp[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j==length2) {
return i - j;
}
return -1;
}