用strtok分割故障

#include #include int main(){ char path[] = "/fs/lost+found"; char* temp; temp = strtok(path,"lost+found"); while(temp != NULL){ printf("\n %s \n",temp); temp = strtok(path,"lost+found"); } return 0; } 

我想提取丢失+找到的字符串。 上面的程序进入无限循环并打印分隔符“lost + found”之前的“/”

[root @ rs]#。/ a.out分段错误

你犯了两个错误(你可以从这里轻松发现)。

  1. strtok()分隔符作为第二个参数。 在你的情况下,这个分隔符不会lost+found但合理/

  2. while块中, strtok函数的第一个参数必须为NULL以使函数继续扫描先前成功调用函数的位置。

最后,您必须使用strcmp()来发现处理后的令牌是否是您正在寻找的字符串。

所以:

  ... while (temp != NULL) { if (strcmp("lost+found", temp) == 0) printf ("%s\n", temp); // found temp = strtok (NULL, "/"); } ... // not found 

来自man 3 strtok:

char * strtok(char * str,const char * delim);

strtok()函数将字符串解析为一系列标记。 在第一次调用strtok()时,应该在str中指定要解析的字符串。 在应该解析相同字符串的每个后续调用中,str应为NULL。

固定:

 #include #include int main(){ char path[] = "/fs/lost+found"; char* temp; temp = strtok(path,"/"); // ^^^ different delimiter do { printf("%s\n", temp); temp = strtok(NULL, "/"); // ^^^^ each subsequent call to strtok with NULL as 1st argument } while (temp != NULL); return 0; } 

它会打印出“fs”和“lost + found”标记。 您可以添加一些检查temp是否当前具有您正在查找的值,然后您可以存储在其他变量中。

delim参数指定一组字符,用于分隔已解析字符串中的标记。

您为strtok提供的第二个参数提供了一组用于标记给定字符串的分隔符,而不是用于提取特定字符串

使用strstr

 temp = strstr(path,"lost+found"); 

这将返回指向您要搜索的子字符串的指针

您无法更改字符串文字, strtok()将修改它正在处理的字符串。