问题描述:
对于字符串a和b,若b是a的子串,返回b在a中的位置(b的首字符在a中对于的下标),否则返回-1。
#include <iostream>
#include <cstring>
using namespace std;
int BF( char *a, char *b)
{
int i = 0;
int j = 0;
while (i <= strlen(a )- 1 && j <= strlen(b )-1)
{
if (a [i] == b [j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == strlen(b))
{
cout <<"匹配成功!"<<endl;
return i-j;
}
cout <<"匹配失败!"<<endl;
return -1;
}
int main()
{
char a[100];
char b[100];
cout <<"请输入字符串a:"<<endl;
cin>>a;
cout <<"请输入字符串b:"<<endl;
cin>>b;
cout << BF(a,b) << endl;
return 0;
}