我正在尝试解析C中的URL查询字符串,我不知道如何优雅地执行它.任何提示或建议将不胜感激:
static void readParams(char * string, char * param, char * value) {
char arg[100] = {0}; // Not elegant, brittle
char value2[1024] = {0};
sscanf(string, "%[^=]=%s", arg, value2);
strcpy(param, arg);
strcpy(value, value2);
}
char * contents = "username=ted&age=25";
char * splitted = strtok (contents,"&");
char * username;
char * age;
while (splitted != NULL)
{
char param[100]; // Not elegant, brittle
char value[100];
char * t_str = strdup(splitted);
readParams(t_str, param, value);
if (strcmp(param, "username") == 0) {
username = strdup(value);
}
if (strcmp(param, "age") == 0) {
age = strdup(value); // This is a string, can do atoi
}
splitted = strtok (NULL, "&");
}
Run Code Online (Sandbox Code Playgroud)
我一直存在的问题是因为strtok函数在最后一个strtok函数似乎打破了while循环之前似乎更聪明.
一般来说,strtok 会破坏源字符串以供其他一些函数使用。这是使用 strtok 标记字符串的简单示例
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MX_SPLIT 128
char **split( char **result, char *working, const char *src, const char *delim)
{
int i;
strcpy(working, src); // working will get chppped up instead of src
char *p=strtok(working, delim);
for(i=0; p!=NULL && i < (MX_SPLIT -1); i++, p=strtok(NULL, delim) )
{
result[i]=p;
result[i+1]=NULL; // mark the end of result array
}
return result;
}
void foo(const char *somestring)
{
int i=0;
char *result[MX_SPLIT]={NULL};
char working[256]={0x0}; // assume somestring is never bigger than 256 - a weak assumption
char mydelim[]="!@#$%^&*()_-";
split(result, working, somestring, mydelim);
while(result[i]!=NULL)
printf("token # %d=%s\n", i, result[i]);
}
Run Code Online (Sandbox Code Playgroud)