有没有办法在C中的多个字符上拆分字符串?

在C中是否有一种方法来分割字符串(使用strtok或任何其他方式),其中分隔符的长度超过一个字符? 我正在寻找这样的东西:

 char a[14] = "Hello,World!"; char *b[2]; b[0] = strtok(a, ", "); b[1] = strtok(NULL, ", "); 

我希望这不会拆分字符串,因为逗号和W之间没有空格。有没有办法做到这一点?

您可以重复调用substr来查找边界字符串的出现位置并沿结果分割。 找到结果后,将指针前进到子字符串的长度并再次搜索。

您可以使用char * strstr(const char *haystack, const char *needle)在字符串中找到分隔符字符串。

 char a[14] = "Hello,World!"; char b[2] = ", "; char *start = a; char *delim; do { delim = strstr(start, b); // string between start and delim (or end of string if delim is NULL). start = delim + 2; // Use lengthof your b string. } while (delim); 

这样的事可能吗? 不保证这会编译。 ;)

 char* strstrtok(char *haystack, char *needle) { static char *remaining = null; char *working; if(haystack) working = haystack; else if(remaining) working = remaining; else return NULL; char *result = working; if(result = strstr(working, needle)) remaining = working + strlen(needle) + 1; return result; }