#include<iostream>
#include<string.h>
using namespace std;
typedef struct
{
char ch[50];
int length;
}SString;
int Index_BF(SString S,SString T,int pos)
{
cout<<"请输入S字符串:"<<endl;
cin>>S.ch;
cout<<"请输入T字符串:"<<endl;
cin>>T.ch;
cout<<"请输入主串中开始进行匹配的位置(首字符位置为1):";
cin>>pos;
S.length=strlen(S.ch);
T.length=strlen(T.ch);
int i=pos,j=1;
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;
}
int main()
{
SString S,T;
char ch;
int pos;
cout<<"是否进行测试(输入y或Y继续,任意其他键结束):";
cin>>ch;
while(ch=='y'||ch=='Y')
{
int result=Index_BF(S,T,pos);
if(result!=0)
cout<<"主串与子串在主串的第"<<result<<"个字符处首次匹配"<<endl;
else
cout<<"匹配失败"<<endl;
cout<<"是否继续测试(输入y或Y继续,任意其他键结束):";
cin>>ch;
}
}
BF算法的实现
最新推荐文章于 2024-08-20 13:11:41 发布