有没有一种方法可以在C语言中拆分多个字符上的字符串?
在C语言中,当分隔符的长度超过一个字符时,是否有方法拆分字符串(使用有没有一种方法可以在C语言中拆分多个字符上的字符串?,c,string,split,C,String,Split,在C语言中,当分隔符的长度超过一个字符时,是否有方法拆分字符串(使用strtok或任何其他方法)?我在找这样的东西: char a[14] = "Hello,World!"; char *b[2]; b[0] = strtok(a, ", "); b[1] = strtok(NULL, ", "); 我不希望分割字符串,因为逗号和W之间没有空格。有没有办法做到这一点?您可以重复调用以查找边界字符串的出现处,然后沿结果分割。找到结果后,将指针向前移动子字符串的长度,然后再次搜索。您可以使用cha
strtok
或任何其他方法)?我在找这样的东西:
char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");
我不希望分割字符串,因为逗号和W之间没有空格。有没有办法做到这一点?您可以重复调用以查找边界字符串的出现处,然后沿结果分割。找到结果后,将指针向前移动子字符串的长度,然后再次搜索。您可以使用
char*strstr(const char*haystack,const char*pinder)
在字符串中定位分隔符字符串
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);
也许是这样的?不保证这会编译。;)
如果你包含<代码> >代码>,它是C++,如果你说“代码> STD::子字符串”,并且包含
char*b[]
,谢谢。但我看不出您第一点的问题。delim
不是递增的,它保留为NULL
,并允许退出循环。问题出在哪里?
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;
}