strtok() and empty fields

时光总嘲笑我的痴心妄想 提交于 2019-12-01 04:23:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2377760/strtok-and-empty-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!