我正在尝试编写一段代码,使用strstr提取在<body>和</body>标签之间的所有单词/字符串。但似乎它只能提取到第一个字符串"quick",然后就停止了。如何让代码在提取第一个字符串后继续提取接下来的字符串?
#include <stdio.h>
#include <string.h>
int main()
{
char feed[] = "The <item> quick </item> brown <item> fox </item> jumps <item> over </item> the <item> lazy dog </item>";
const char needle[] = "<item>";
const char popo[] = "</item>";
char *ret;
char *ter;
int n;
n = 0;
while (feed[n] != '\0')
{
ret = strstr(feed, needle)+6;
ter = strstr(ret, popo);
size_t len = ter - ret;
char *res = (char*)malloc(sizeof(char)*(len+1));
strncpy(res, ret, len);
res[len] = '\0';
printf("%s",res);
n++;
}
return 0;
}
malloc()
。ret = strstr(feed, needle)+6;
这个操作很危险,如果strstr()
返回NULL
,你最终会得到(void *)0x06
而不是(void *)0x00
,解引用这个地址会出问题。此外,使用memcpy()
替代strncpy()
,像这样memcpy(res, ret, len)
,在执行之前检查res != NULL
。 - Iharob Al Asimiret ! = NULL
后,您可以添加<item>
的长度,请参考我的答案。 - Iharob Al Asimi