#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main()
{
const char *str = "abcd1233abcd";
const char *p = NULL;
int cnt = 0;
//找到了,这里错了,每次都是从str中搜索“abcd”,所以无线循环了
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;
}
结果是无线循环,哪里错误了?
改正如下:
const char *str = "abcd1233abcd";
const char *p = str;
int cnt = 0;
while (p = strstr(p, "abcd"))
{
cnt++;
p = p + strlen("abcd");
}
为什么这个做法是正确的呢?