7

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.

Rio
  • 14,182
  • 21
  • 67
  • 107
  • 2
    So save a copy of the string before you call `strtok()`. – Duck Mar 06 '12 at 05:59
  • @S.O users I my perception this is a very nice question. In addition to predicting other methods it will be better if someone reason for why the sscanf(contents, "%s&%s", arg, value); doesn't work – Muthu Ganapathy Nathan Mar 06 '12 at 06:26
  • @EAGER_STUDENT like I said in my answer, asking `scanf` to scan for `%s` causes it to scan up to the next whitespace. So it won't stop on an ampersand. – Tommy Mar 06 '12 at 06:56

3 Answers3

9

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);
Donotalo
  • 12,748
  • 25
  • 83
  • 121
1

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • When I try to abstract the sub-parsing into a new function passing in a strduped version of the split, it fails. Why is this? I've added code to the above to fix. – Rio Mar 06 '12 at 06:28
0

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
RootsAmongRuins
  • 101
  • 1
  • 7