代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//查找big中出现smal的次数
void findstr(char*big ,char* smal,int pos[],int *nmb)
{
int i,j,lenb,lens;
lenb = strlen(big);
lens = strlen(smal);
*nmb = 0;
if(lens > lenb)
return;
i = 0;
while(i < lenb-lens+1)
{
for (j = 0; j < lens;j++)
{
if(big[i+j] != smal[j])
break;
}
if (j == lens) //说明找到
{
pos[*nmb] = i;
(*nmb)++;
i += lens;
}else
i++;
}
}
int main()
{
char big[100];
char small[10];
int pos[20];
int nmb=0;
gets(big); //读取长字符串
gets(small);//读取子字符串
findstr(big,small,pos,&nmb);
printf("%d",nmb);
return 0;
}
从母串的第一个字符开始和子串匹配,如果和子串相同则计数,然后从结束处开始后续比较;如果有字符不匹配,则从起点的下一个字符开始继续比较
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
scanf("%s",a);
char * c = a;
char b[10];
scanf("%s",b);
char * d = b;
int n;
int num = 0;
n = strlen(d);
while(strlen(c) > 0)
{
if(strncmp(c,d,n) == 0)
{
num++;
c += n;
}
else
{
c++;
}
}
printf("%d\n",num);
return 0;
}