问题 A: 算法4-5:求子串位置的定位函数
题目描述
输出
每组数据输出2行,第一行是S中每次比较的字符,第二行是后一个字符串在前一个字符串中的位置,如果不匹配,则输出0。
样例输入
string str
thisisalongstring isa
nosubstring subt
样例输出
str
1
thisisisa
5
nosubsubsttring
0
#include<iostream>
#include<string.h>
#define MAXLEN 10000
using namespace std;
typedef struct {
char ch[MAXLEN];
int length;
}SString;
int index_BF(SString S, SString T, int pos)
{
int i, j;
i = pos;
j = 0;
while (i < S.length&&j < T.length)
{
if (S.ch[i] == T.ch[j])
{
cout << S.ch[i];
++i;
++j;
}
else
{
cout << S.ch[i];
i = ++pos;
j = 0;
}
}
if (j == T.length)
{
return pos;
}
else
{
return -1;
}
}
int main()
{
SString S, T;
int k, i;
for (i = 0; i < 3; i++)
{
cin >> S.ch >> T.ch;
S.length = strlen(S.ch);
T.length = strlen(T.ch);
k = index_BF(S, T, 0);
cout << endl;
cout << k + 1;
}
return 0;
}