用标准库函数实现:
//输入一个字符串(保存在数组b中),查找字符串a(*a="ab")出现的次数,将出现次数保存到c中
//---------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char b[80];
char *p=b,*a="ab",*s;
int c=0;
gets(b);
do{
if ((s=strstr(p,a)))
c++;
p=(s+2);
}while (s) ;
printf("%d",c);
return 0;
}
//---------------------------------------------------------------------------
不用库函数
#include <stdio.h>
int strc(const char *a,const char *b)//统计在a中b出现的次数
{
int c=0;
const char *s,*p,*ts;
p=a,ts=b;
do
{
//if (*p*(*(p+1))==0) break;
if (*p==*ts&&*(p+1)==*(ts+1)) c++;
p+=2; //b的长度为2
}
while (*p&&*(p+1));
return c;
}
int main(void)
{
char *b="ab";
char a[80];
scanf("%s",a);
puts(a);
printf("%d",strc(a,b));
return 0;
}
参考资料:测试环境 loongson-2E + Debian linux + gcc
本回答被提问者和网友采纳