#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#define MAXLEN 255
#define OK 1
#define ERROR 0
#define Status int
#define SElemType char
#include<stdlib.h>
using namespace std;
//----串的顺序存储结构----//
typedef struct
{
char ch[MAXLEN+1];
int length;
}SString;
//BF算法
int Index_BF(SString S,SString T,int pos)
{
//返回模式T在主串S中第pos个字符开始第一次出现的位置。若不存在,则返回值为0
//其中,T非空,0<=pos<==S.length-1
int i,j;
i=pos-1;j=0; //初始化
S.length=strlen(S.ch);
T.length=strlen(T.ch);
while(i<=S.length-1&&j<=T.length-1) //两个串均未比较到串尾
{
if(S.ch[i]==T.ch[j]) //继续比较后继字符
{
++i;
++j;
}
else //指针后退重新开始匹配
{
i=i-j+1;
j=0;
}
}
if(j>T.length-1)
return i-T.length; //匹配成功
else
return -1; //匹配失败
}
//实现
int main()
{
SString S,T;
int p;
//输入串S,T
printf("输入母串S\n");
scanf("%s",S.ch);
printf("输入子串T\n");
scanf("%s",T.ch);
printf("输入从第p个字符开始匹配,p=\n");
scanf("%d",&p);
printf("从第%d位开始匹配\n",Index_BF(S,T,p)+1);
return 0;
}
题目:用BF算法实现串操作的模式匹配算法
代码: