朴素模式匹配
//封装一个字符串
typedef struct String
{
const char *string;
unsigned long count;
}String, *StringPtr;
//查找函数
void FindLocation(StringPtr src/*主串*/, StringPtr tar/*子串*/, unsigned long *pos/*返回位置*/)
{
unsigned long i = 0;
unsigned long j = 0;
while (i < src->count && j < tar->count)
{
if (src->string[i] == tar->string[j])
{
i++;
j++;
}
else
{
j = 0;
i = i - j + 1;
}
}
if (j == tar->count)
{
(*pos) = i - j + 1;
}
else
{
(*pos) = 0;
}
}
调用示例
int main(int argc, const char * argv[])
{
StringPtr S = (StringPtr)malloc(sizeof(String));
S->string = "abcdzhang";
S->count = strlen(S->string);
StringPtr s = (StringPtr)malloc(sizeof(String));
s->string = "zhang";
s->count = strlen(s->string);
unsigned long *pos = (unsigned long *)malloc(sizeof(unsigned long));
(*pos) = 0;
FindLocation(S, s, pos);
if ((*pos))
{
printf("location is %lu\n",*pos);
}
else
{
printf("not found!\n");
}
return 0;
}