如何来标记含有用strtok_r空值的字符串 [英] How to tokenize a string containing null values using strtok_r

查看:737
本文介绍了如何来标记含有用strtok_r空值的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些逗号分隔值的字符串。该值可以或可以不为空。这样的:

I have a string which contains some comma separated values. The value may or may not be NULL. like :

strcpy(result, "Hello,world,,,wow,");

我要打印接受空值了。我怎样才能同时使用strtok_r这给了我NULL值也继续进行。

I want null values to be printed accepted too. How can I proceed while using strtok_r which gives me NULL values too.

我试过这样:

#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)

我知道为什么它给分段错误。我想要的解决方案,使输出为这样的:

I know why it is giving Segmentation fault. I want the solution so that output is like:

1
Hello
2
World
3
*
4
*
5
wow

我想 * 要打印的空令牌,但空令牌甚至没有提取。

I want * to be printed for the null tokens but null tokens are not even extracted.

推荐答案

从strtok_r手册页:

From strtok_r man page:

的两个或更多个连续分隔符分析的字符串中的序列被认为是一个单一的分隔符。

A sequence of two or more contiguous delimiter characters in the parsed string is considered to be a single delimiter.

所以它不会在你的情况下工作。但是你可以用code像这样的:结果

So it won't work in your case. But you can use code like this one:

#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;
}

这篇关于如何来标记含有用strtok_r空值的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆