#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "time.h"
#include <sys/stat.h>
int sub_ncount(char *mystr/*in*/, char *sub/*in*/, int *ncount/*out*/) //mystr为母串,sub为字串。ncount统计出现次数
{
int tmpcount = 0;
char *p = mystr;
if (mystr == NULL || sub == NULL || ncount == NULL)//判断传入参数是否正确
{
printf("func sub_ncount() mystr == NULL || sub == NULL || ncount == NULL", -1);
return -1;
}
while (*p != '\0')//返回移动过的p,若不为空串则进行操作
{
p = strstr(p, sub);
if (p != NULL)
{
tmpcount++;
p += strlen(sub);//如果p不为空则字串在头,需要移动指针,再进行查找。
}
else
{
break;
}
}
*ncount = tmpcount;
return 0;
}
int main()
{
char buf[] = "he,he ,ledaad,he";
int count;
sub_ncount(buf, "he", &count);
printf("%d\n", count);
// printf("%s\n", p);
}
c语言-求字串在母串中出现的次数
最新推荐文章于 2022-12-05 09:39:33 发布