拆分C字符串到使用sscanf的令牌 [英] Split C string into tokens using sscanf
问题描述
我想一个字符串分割成令牌,但有些递归。我试图解析:
I'm trying to split a string into tokens but somewhat recursively. I am trying to parse:
"content=0&website=Google"
让我有办法拿出的参数和值。如果我尝试 strtok的
我最终摧毁我要解析两次字符串。所以,我想
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);
作为第一关,希望能解析 ARG
了,但失败了,而 ARG
包含整个字符串。我试着用%S \\&放大器;%的
想着&安培;
是一个保留字,但没有运气
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.
帮助!
编辑:
这是我的strtok黑客:
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, "&");
}
但它不工作,因为分裂的 strtok的
末成为gobbldygook。
but it doesn't work because splitted's strtok
at the end becomes gobbldygook.
推荐答案
下面是一个似乎工作的解决方案:
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);
这篇关于拆分C字符串到使用sscanf的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!