子串的定位操作通常称为串的模式匹配,它求的是子串(常称模式串)在主串中的位置。这里采用定长顺序存储结构,给出一种不依赖于其他串操作的
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct sstring{
char ch[256];
int len;
}sstring;
//在母串a中寻找子串
int matEle(sstring *a,sstring *b)
{
int i=0;//母串的下标
int j=0;//子串的下标
int count=0,note=0;//用于计数
int len1=strlen(a->ch);//母串的长度
int len2=strlen(b->ch);//子串的长度
while(i<=len1)
{
note=i;
while(a->ch[i]==b->ch[j])
{
i++;j++;
count++;
}
if(count!=len2)
{
j=0;
++note;
i=note;
count=0;
}
else
{
return note;
break;
}
}
}
int main()
{
sstring *a=(sstring *)malloc(sizeof(sstring *));
sstring *b=(sstring *)malloc(sizeof(sstring *));
strcpy(a->ch,"aaabbbccaaabbbddd");
strcpy(b->ch,"bbbdd");
int res=matEle(a,b);
printf("%d ",res);
return 0;
}
暴力匹配算法。