Strtok () and empty fields

I serialize some C structure to a string and deserialize it with strtok() . But, unfortunately, strtok() does not detect empty fields (for example, 1: 2 :: 4).

Is there an alternative feature?

+4
source share
3 answers

There is strsep in linux.

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

+9
source

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

+6
source

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

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 */ } 

Using strsep (recognizes ""):

 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 */ } 
0
source

Source: https://habr.com/ru/post/1303097/


All Articles