#include<iostream>
#include<string>
using namespace std;
int BF(string& S, string& T)
{
int i = 0; int j = 0;
while (i < S.length() && j < T.length()) {
if (S[i] == T[j]) {
i++; j++;
}
else {
i = i - j + 1; //回溯
j = 0;
}
}
if (j >= T.length()) {
cout << "已查询到!" << endl;
return i - T.length();
}
else {
cout << "未查询到!" << endl;
return -1;
}
}
int main()
{
cout << "请输入主串:" << endl;
string B; cin >> B;
cout << "请输入模式串:" << endl;
string T; cin >> T;
int flag = BF(B, T);
if (flag == -1) {
cout << "模式串在主串之中不存在!" << endl;
}
else {
cout << "模式串在主串之中存在!" << endl;
cout << "起始位置为:" << flag + 1 << endl;
}
system("pause");
return 0;
}