I need a mix of strtok and strtok_single

前端 未结 2 615
你的背包
你的背包 2020-12-06 15:49

I have the following string that I am trying to parse for variables.

char data[]=\"to=myself@gmail.com&cc=youself@gmail.com&title=&content=how ar         


        
2条回答
  •  Happy的楠姐
    2020-12-06 16:21

    You haven't exactly told us what you mean by "this works fine", though it seems sufficient to say that you want to parse an application/x-www-form-urlencoded string. Why didn't you say so in the first place?

    Consider that the first field, key, may be terminated by the first of either '=' or '&'. It would be appropriate to search for a token that ends in either of those characters, to extract key.

    The second field, value, however, isn't terminated by an '=' character, so it's inappropriate to be searching for that character to extract value. You'd want to search for '&' only.

    Sure. You could use strtok to parse this, however I'm sure there are many more suitable tools. strcspn, for example, won't make any changes to data, which means you won't need to make a copy of data as you are...

    #include 
    #include 
    
    int main(void) {
        char data[]="to=myself@gmail.com&cc=youself@gmail.com&title=&content=how are you?&signature=best regards.";
    
        char *key = data;
        do {
            int key_length = strcspn(key, "&=");
    
            char *value = key + key_length + (key[key_length] == '=');
            int value_length = strcspn(value, "&");
    
            printf("Key:   %.*s\n"
                   "Value: %.*s\n\n",
                   key_length,   key,
                   value_length, value);
    
            key = value + value_length + (value[value_length] == '&');
        } while (*key);
        return 0;
    }
    

提交回复
热议问题