在str1串中查找str2出现的次数?

来源:百度知道 编辑:UC知道 时间:2024/05/30 15:24:11
求如何实现??

#include <stdio.h>

void main()
{
char *str1 = "acbabcabdabe";
char *str2 = "ab";
char *p1,*p2;
int s = 0;
p1 = str1;
p2 = str2;
while(*p1 != '\0')
{
if(*p2 == *p1)
{
while(1)
{
p1 = p1+1;
p2 = p2+1;
if(*p2 == *p1)
{
if(*(p2+1) == '\0')
{
s = s+1;
p2 = str2;
break;
}
else
{
continue;
}
}
else
{
p2 = str2;
break;
}
}
}
else
{
p1 = p1+1;
}
}
printf("%d\n",s);
}

这个题可以用KMP算法,这样效率比较高