#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main()
{
const char *str = "abcd1233qabcd34534564abcd2543";
const char *p = NULL;
int cnt = 0;
while (p = strstr(str, "abcd"))
{
cnt ++;
printf("cnt : %d\n",cnt);
p = p + strlen("abcd");
if (*p == '\0')
break;
}
if (p != NULL)
printf("cnt:%d\n", cnt);
else
printf("cnt is 0\n");
return 0;
}
结果是无线循环,哪里错误了?
为什么这个做法是正确的呢?
void getCount(const char * p,const char *buf,int *cnt)
{
*cnt = 0;
while(p)
{
p = strstr(p,buf);
if (p)
{
++*cnt;
p = p + strlen(buf);
}
else
break;
}
}
int main(void)
{
const char *p1 = "1234abcd123";
const char *buf = "abcd";
int count;
getCount(p1,buf,&count);
printf("%d\n",count);
return 0;
}