计算机教材《数据结构(C语言版)》——严蔚敏教授编写的,我根据此书中串的那章内容及思想方法,敲了BF算法的代码,如下:
#include<stdio.h>
#include<string>
#include<stdlib.h>
#pragma warning(disable:4996)
#define ERROR 0
#define OVERFLOW 0
#define OK 1
typedef int Status;
typedef struct {
char* data;
int length;
}HString;
//对串进行赋值操作
Status strAssign(HString& T, char* chrs) {
//释放掉T中的原数据
if (T.data) {
free(T.data);
T.length = 0;
}
//定义一个temp数组用来接收chrs的元素
char* temp = chrs;
int len = 0;
while (*temp) {
len++;
temp++;
}
//当chrs是一个空的数组后,进行下列操作
if (len == 0) {
T.data = NULL;
T.length = len;
return 0;
}
//如果不为空,分配内存空间
else {
T.data = (char*)malloc((len+2) * sizeof(char));
if (!T.data) {
exit(OVERFLOW);//分配失败
}
for (int i = 1; i <= len; i++, chrs++) {
T.data[i] = *chrs;
}
T.length = len;
return OK;
}
}
//BF算法
Status index(HString& S, HString& T, int pos) {
int i = pos;
int j = 1;
printf("主串S的长度是:%d\n", S.length);
printf("子串T的长度是:%d\n", T.length);
while (i <= S.length && j <= T.length) {
if (S.data[i] == T.data[j]) {
++i; ++j;
}
else {
i = i - j + 2; j = 1;
}
}
if (j >=T.length) {
return i - T.length;
}
}
int main() {
HString S;
HString T;
int pos = 1;//对比开始的下标
char ch1[100]; //主串
char ch2[100]; //子串
printf("请输入主串:\n");
scanf("%s", &ch1);
strAssign(S, ch1);
printf("请输入子串:\n");
scanf("%s", &ch2);
strAssign(T, ch2);
int number=index(S, T, pos);
printf("子串在主串的位置是:%d\n", number);
return 0;
}
执行程序:
运行成功