我有一个字符串,其中包含一些逗号分隔的值。该值可能为 NULL,也可能不为 NULL。像:
strcpy(result, "Hello,world,,,wow,");
我也希望打印接受空值。使用 strtok_r 时如何继续,它也给我 NULL 值。
我尝试过这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char result[512] = { 0 };
strcpy(result, "Hello,world,,,wow");
char *token, *endToken;
int i = 0;
token = strtok(result, ",");
while (i < 5) {
printf("%d\n", ++i);
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
输出是:
1
Hello
2
world
3
wow
4
Segmentation fault (core dumped)
我知道为什么会出现段错误。我想要解决方案,以便输出如下:
1
Hello
2
World
3
*
4
*
5
wow
我希望为空标记打印 *
,但甚至不提取空标记。
最佳答案
来自 strtok_r 手册页:
A sequence of two or more contiguous delimiter characters in the parsed string is considered to be a single delimiter.
所以它不适用于你的情况。但您可以使用如下代码:
#include <stdio.h>
#include <string.h>
int main(void) {
int i = 0;
char result[512];
char *str = result, *ptr;
strcpy(result, "Hello,world,,,wow");
while (1) {
ptr = strchr(str, ',');
if (ptr != NULL) {
*ptr = 0;
}
printf("%d\n", ++i);
printf("%s\n", str);
if (ptr == NULL) {
break;
}
str = ptr + 1;
}
return 0;
}
关于c - 如何使用 strtok_r 对包含空值的字符串进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524489/