#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define maxSize 6
struct Str
{
char *ch;
int length;
};
int index(Str *&substr,Str str)
{
int i = 0, j = 0, k = 0;
while (i < str.length && j< substr->length-1 ) // 子串比较到‘\0’之前的位置即可
{
if (str.ch[i] == substr->ch[j])
{
++i;
++j;
}
else
{
j = 0; // 子串归0
i = ++k; // 记录每次主串开始的地方
}
}
if (j >= substr->length-1) // 当j的位置 大于 等于子串长度时候 比较完毕
{
return k;
}
else
{
return 0;
}
}
int main()
{
Str str1 ;
str1.ch = (char *)malloc(sizeof(char)*7);
strcpy_s(str1.ch,7, "abcdef");
str1.length = 7;
Str *str2 = (struct Str*)malloc(sizeof(struct Str));
str2->ch = (char *)malloc(sizeof(char) * 4);
strcpy_s(str2->ch, 4,"def");
str2->length =4;
int position = index(str2,str1);
printf("元素匹配的位置是: %4d", position);
}
字符串匹配之BF算法
最新推荐文章于 2024-02-02 00:12:54 发布