我想用“;”将字符串分割成标记。但我有一个问题,例如某些 token 为空/空; 123;123132;;;232;232323;;;;1; 所以我不能使用 strtok 因为合并相邻的分隔符。我看到您发布了这个解决方案:
include <string.h>
char *data = "this&&that&other";
char *next;
char *curr = data;
while ((next = strchr(curr, '&')) != NULL) {
/* process curr to next-1 */
curr = next + 1;
}
/* process the remaining string (the last token) */
但我不明白,因为当我执行 next-1 来获取第一个值时,我只得到该值的第一个单词,而不是整个值。 你能帮我吗?你知道如何分割它吗? 我正在用 C ansi 编程。我在另一篇文章中看到存在一个 strsep 函数,这似乎正是我所需要的,但在 C ansi 库中不包含此函数。 谢谢并抱歉我的英语:)
最佳答案
我认为这就是你想要的:-
#include <stddef.h>
#include <string.h>
#include <stdio.h>
char* mystrsep(char** input, const char* delim)
{
char* result = *input;
char* p;
p = (result != NULL) ? strpbrk(result, delim) : NULL;
if (p == NULL)
*input = NULL;
else
{
*p = '\0';
*input = p + 1;
}
return result;
}
int main()
{
char str[] = "123;123132;;;232;232323;;;;1;";
const char delimiters[] = ";";
char* ptr;
char* token;
ptr = str;
token = mystrsep(&ptr, delimiters);
while(token)
{
printf("%s\n",token);
token = mystrsep(&ptr, delimiters);
}
return 0;
}
关于c - 如何按 '&' 将字符串拆分为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17992703/