[英]How to tokenize a string containing null values using strtok_r
我有一个字符串,其中包含一些逗号分隔值。 该值可能为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)
我知道它为什么会出现Segmentation故障。 我想要解决方案,以便输出如下:
1
Hello
2
World
3
*
4
*
5
wow
我希望*
为空标记打印,但是甚至不提取空标记。
来自strtok_r手册页:
解析后的字符串中的两个或多个连续分隔符字符的序列被视为单个分隔符。
所以它不适合你的情况。 但你可以使用这样的代码:
#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;
}
如果你没有strsep()
你可以自己动手。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char result[512] = "Hello,world,,,wow";
char *token, *endToken;
int i = 0;
token = result;
do {
endToken = strchr(token, ',');
if (endToken)
*endToken = '\0'; // terminate token
printf("%d\n", ++i);
if (*token == '\0') // substitute the empty string
printf("*\n");
else
printf("%s\n", token);
if (endToken)
token = endToken + 1;
} while (endToken);
return 0;
}
节目输出:
1
Hello
2
world
3
*
4
*
5
wow
要使strtok找到令牌,必须有第一个不是分隔符的字符。 它只在到达字符串末尾时返回NULL,即当它找到'\\0'
字符时。
为了确定令牌的开始和结束,该函数首先从起始位置扫描未包含在分隔符中的第一个字符(它成为令牌的开头) 。 然后从令牌的开头开始扫描包含在分隔符中的第一个字符,这将成为令牌的结尾。 如果找到终止空字符,扫描也会停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.