Split C string into tokens using sscanf

流过昼夜 提交于 2019-11-28 04:06:36

问题


I'm trying to split a string into tokens but somewhat recursively. I am trying to parse:

"content=0&website=Google"

so that I have a way to take out the parameters and values. If I try strtok I end up destroying the string I want to parse twice. So I tried

char *contents = "content=0&website=Google"
char arg[100];
char value[100];
sscanf(contents, "%s&%s", arg, value);

as a first pass, hoping to parse arg again, but it fails, and arg contains the entire string. I tried using "%s\&%s" thinking & was a reserved word, but no luck there.

Help!

Edit:

This was my strtok hack:

static void readParams(char * string, char * param, char * value) {
    printf("This is the string %s\n",string);
    char * splitted = strtok (string,"=");

    while (splitted != NULL)
    {
        printf("This is the string %s\n",splitted);
        splitted = strtok (NULL, "=");
        // Then do some saving to param and value
    }
}
char * splitted = strtok (contents,"&");
int counter = 0;

while (splitted != NULL)
{
    char * t_str = strdup(splitted);
    readParams(t_str, param, value);
    splitted = strtok (NULL, "&");
}

but it doesn't work because splitted's strtok at the end becomes gobbldygook.


回答1:


Here is a solution that seems to work:

char *contents = "content=0&website=Google";
char arg[100] = {0};
char value[100] = {0};
sscanf(contents, "%[^&]&%s", arg, value);
printf("%s\n%s\n", arg, value);



回答2:


scanf is more primitive than you seem to think — %s will match everything up to the next whitespace. Your best solution is probably to stick with strtok but throw it only content you've strduped from the authoritative original.




回答3:


I recommend something similar to the following:

char t_str[100];
strncpy(t_str, contents, 100);
//now strtok() on t_str, original contents will be preserved


来源:https://stackoverflow.com/questions/9578611/split-c-string-into-tokens-using-sscanf

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