串朴素模式匹配算法实现
#include<stdio.h>#include<stdlib.h>
#include<stdbool.h>
#define MAXSTRLEN 255
// 存储结构
typedef unsigned char SString[MAXSTRLEN + 1];
// 朴素匹配模式
int Index(SString S, SString T, int pos){
int i = pos;
int j = 1;
while(i<S[0] && j<=T[0]){
if(S[i] == T[j]){
++i;
++j;
}else{
i = i-j+2;
j = 1;
}
}
if(j>T[0]){
return i-T[0];
}
return 0;
}
bool StrAssign(SString str, char *src){
char * c = src;
for(int i=0; *c!='\0'; ++i, ++c){
if(0==i){
str[0] = 0;
}else{
str[0] = 0;
for(int j=1; j<=i; j++){
str[j] = src[j-1];
str[0] +=1;
}
}
}
}
void main(){
SString S;
SString T;
char a[] = "abbacdefg";
char b[] = "acd";
// 给串分配元素顺便牺牲掉第一个位置来记录串的实际长度
StrAssign(S, a);
StrAssign(T, b);
int pos = Index(S, T, 3);
if (pos != 0)
printf("模式匹配成功,找到位置为%d\n", pos);
else
printf("模式匹配失败");
return 0;
}