strtok() and empty fields
Asked Answered
O

3

5

I am serializing some C structure to string and than deserializing it with strtok(). But, unfortunately, strtok() don't detect empty fields (eg 1:2::4).

Is there any alternative function?

Ogdon answered 4/3, 2010 at 8:20 Comment(0)
A
12

On linux there's strsep.

The strsep() function was introduced as a replacement for strtok(), since the latter cannot handle empty fields. However, strtok() conforms to C89/C99 and hence is more portable.

Alacrity answered 4/3, 2010 at 8:28 Comment(1)
strsep() is also thread-safe (or can be made that way), which strtok() is very very not.Cf
A
9

You can use strchr (for just one delimiter character) or strcspn (for a group of possible delimiters) to find the next delimiter, process the token, and then just step one character forward. Do this in a loop and you have what you need.

Arthromere answered 4/3, 2010 at 8:26 Comment(0)
R
-1

Drakosha gave the correct answer. I want to add an example for both variants.

With strtok:

char *token;
char *tmp_string;
char delimiter[10] = " |,.:";
strcpy (tmp_string, "1:2::4");
token = strtok(tmp_string, delimiter); // first token
while(token != NULL) {
    i++;
    printf ("i=%d\tToken: len(%d)\t%s", i, strlen(token), token);
    // do something
    token = strtok(NULL, delimiter); /* next token */
}

With strsep (will recognize ""):

char *token;
char *tmp_string;
char delimiter[10] = " |,.";
strcpy (tmp_string, "1:2::4");
token = strsep(&tmp_string, delimiter); // first token
while(token != NULL) {
    i++;
    printf ("i=%d\tToken: len(%d)\t%s", i, strlen(token), token);
    // do something
    token = strsep(&tmp_string, delimiter); /* next token */
}
Rampage answered 12/5, 2015 at 9:20 Comment(2)
char *tmp_string; strcpy (tmp_string, "1:2::4"); will cause memory issues...Remonstrant
Why not simply on the stack: char tmp[] = "1:2::4"; - in contrast, the delimiter does not need to be placed there, simply can do strtok(tmp, ":");...Split

© 2022 - 2024 — McMap. All rights reserved.