完整代码:
#include <iostream>
using namespace std;
#define MAXLINE 255
//定义存储结构
typedef struct {
char ch[MAXLINE+1]; //存储串的一维数组
int length; //串的当前长度
}SString;
//创建串
bool CreatString(SString &S){
int i=1;
char a;
cin>>a;
while (a != '0'){
if(S.length == MAXLINE){
cout<<"字符串已满";
return false;
} else{
S.ch[i] = a; i++;
}
S.length++;
cin>>a;
}
return true;
}
//字符串匹配的BF算法
int Index_BF(SString S,SString T){
int i=1,j=1; //从第pos个位置开始比较
while (i<=S.length && j<=T.length){
if(S.ch[i] == T.ch[j]){++i; ++j;} //主串和子串依次匹配下一个字符
else{i = i-j+2; j = 1;} //主串、子串指针回溯重新开始匹配
}
if(j >= T.length) return i-T.length; //匹配成功,返回匹配的第一个字符下标
else return 0; //匹配不成功
}
//获取next的值
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];
}
}
//获取nextval的值
void get_nextval(SString T, int *nextval){
int i=1,j=0;
nextval[1]=0;
while (i<T.length){
if(j == 0 || T.ch[i] == T.ch[j]){
i++;
j++;
if(T.ch[i] != T.ch[j]) nextval[i] = j;
else nextval[i] = nextval[j];
} else
j = nextval[j];
}
}
//KMP算法
int Index_KMP(SString S,SString T){
int *next = new int(T.length);
get_next(T,next); //获取next值
//get_nextval(T,next); 获取nextval值
int i=1,j=1; //从第pos个位置开始比较
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; //匹配不成功
}
int main() {
SString S,T;
char a;
int result,result2;
cout<<"依次输入字符,创建字符串S(输入0结束):"<<endl;
CreatString(S);
cout<<"依次输入字符,创建匹配字符串T(输入0结束):"<<endl;
CreatString(T);
cout<<"BF算法:"<<endl;
result = Index_BF(S,T);
if(result == 0) cout<<"字符串匹配不成功"<<endl;
else cout<<"字符串匹配位置为第"<<result<<"个"<<endl;
cout<<"KMP算法:"<<endl;
result2 = Index_KMP(S,T);
if(result2 == 0) cout<<"字符串匹配不成功"<<endl;
else cout<<"字符串匹配位置为第"<<result2<<"个"<<endl;
return 0;
}
运行结果图: