#include<iostream>
using namespace std;
int BF(char S[], char T[]){
int index = 0;
int i = 0;
int j = 0;
while((S[i] !='\0') && (T[j] != '\0') && (strlen(S)-i+1>=strlen(T)-j+1)){
if (S[i]==T[j]) {i++; j++;}
else {index++; i=index; j=0; }
}
if (T[j]=='\0') return index+1;
else return 0;
}
int main(){
char S[100],T[100];
int m,n,i;
cout<<"请输入主串S的长度 :";
cin>>m;
cout<<"请输入模式串T的长度:";
cin>>n;
cout<<"主串S为 :";
do {
gets(S);
} while( !S[0] );
cout<<"模式串T为:";
do {
gets(T);
} while( !T[0] );
int a = BF(S,T);
if(a == 0){
cout<<"模式串与主串不匹配!"<<endl ;
}
else{
cout<<"模式串与主串从第"<<a<<"位开始匹配"<<endl ;
}
using namespace std;
int BF(char S[], char T[]){
int index = 0;
int i = 0;
int j = 0;
while((S[i] !='\0') && (T[j] != '\0') && (strlen(S)-i+1>=strlen(T)-j+1)){
if (S[i]==T[j]) {i++; j++;}
else {index++; i=index; j=0; }
}
if (T[j]=='\0') return index+1;
else return 0;
}
int main(){
char S[100],T[100];
int m,n,i;
cout<<"请输入主串S的长度 :";
cin>>m;
cout<<"请输入模式串T的长度:";
cin>>n;
cout<<"主串S为 :";
do {
gets(S);
} while( !S[0] );
cout<<"模式串T为:";
do {
gets(T);
} while( !T[0] );
int a = BF(S,T);
if(a == 0){
cout<<"模式串与主串不匹配!"<<endl ;
}
else{
cout<<"模式串与主串从第"<<a<<"位开始匹配"<<endl ;
}
}
----------------------------------------------------程序测试---------------------------------------------------
请输入主串S的长度 :10
请输入模式串T的长度:5
主串S为 :qwertyuiop
模式串T为:ertyu
模式串与主串从第3位开始匹配
请按任意键继续. . .