Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tokenize a string containing null values using strtok_r

Tags:

c

string

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

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

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

I tried this :

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

and the output is :

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.

like image 519
adnaan.zohran Avatar asked Apr 13 '26 14:04

adnaan.zohran


2 Answers

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.

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;
}
like image 102
nsilent22 Avatar answered Apr 16 '26 09:04

nsilent22


If you don't have strsep() you can roll your own.

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

Program output:

1
Hello
2
world
3
*
4
*
5
wow
like image 32
Weather Vane Avatar answered Apr 16 '26 08:04

Weather Vane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!