是否可以将多个字符一起作为分隔符使用?
我想用一个字符串来作为另一个字符串的分隔符。
char * input = "inputvalue1SEPARATORSTRINGinputvalue2SEPARATORSTRINGinputvalue2";
char * output = malloc(sizeof(char*));
char * delim = "SEPARATORSTRING";
char * example()
{
char * ptr = strtok(input, delim);
while (ptr != NULL)
{
output = strcat(output, ptrvar);
output = strcat(output, "\n");
ptr = strtok(NULL, delim);
}
return output;
}
printf
打印的返回值:
inputvalue1
inputvalue2
inputvalue3
char * output = malloc(sizeof(char*));
是错误的。 - Sourav Ghoshstrtok
。您需要使用strstr
来定位要搜索的字符串中的分隔符子字符串,然后根据分隔符字符串的长度来拆分字符串。为什么?strtok
分隔符字符串中的任何一个字符都是分隔符。事实上,您有很多分隔符并不意味着strtok
会将所有分隔符字符组合成单个分隔符。您需要找到搜索字符串中的分隔符字符串的子字符串。这需要使用strstr
。 - David C. Rankin