c - 如何使用 strtok_r 对包含空值的字符串进行标记

标签 c string

我有一个字符串,其中包含一些逗号分隔的值。该值可能为 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/

相关文章:

c - 在 printf 中通过 %s 在 c 中打印 int

c - 在循环中填充数组

c# - C# 或 C 的高性能 RSA 实现

c - 使用 GLUT 和 C 的闪烁 2D 纹理

c - 我需要从一个单词中获取字母

c++ - 如何在 C++ 中将 std::string 转换为十六进制字符数组?

windows - 使用批处理删除文件夹中除列表中文件之外的所有文件

c - 在外部汇编程序中修改 C 数组

c - 变量的值被覆盖

c - 为什么我必须通过引用传递字符串才能更改它指向的位置?