c - 使用 strtok_r() 从数组中提取多个字符串
问题描述
我正在尝试使用 strtok_r() 从传递给我的函数的 char 数组中解析并同时存储一些数据。第一个变量的提取按预期工作,当我到达第二个变量时,我只得到出现在令牌和字符串的 NULL 终止符之间的部分部分。在这里,我试图获取 'to=' 之后的值、'paw=' 之后的密码和 'tz=' 之后的数字。第一个也是最后一个工作,但是我在“爪子”的任何一侧都丢失了标记,并且似乎无法提取“=”另一侧的文本。我每次都留下NULL。
这是解析这样的字符串的最佳方法吗?我有一个使用 strtok() 的工作版本,但它使用了很多变量,因为我基本上每次都必须存储一个临时值,然后在每个变量上运行令牌 - 它需要两个单独的案例,我希望所有事情都在里面处理一个案例。我也尝试过使用 strchr() 但这也很麻烦并且需要很多临时变量。
感谢您的任何建议,我期待着讨论!
下面是我的代码,它可以编译(需要 string.h)
int main(int argc, char **argv){
char resp[] = "INCOMING,1,443:GET /send?to=12&paw=password&tz=3 HTTP/1.1";
char *arg;
char *p_arg;
char *temp;
char *p_temp;
printf("resp is: %s\n",resp); //full response
arg = strtok_r(resp, ",", &p_arg);
arg = strtok_r(NULL, ",", &p_arg);
printf("first num = %s\n", arg); //get the first number
strtok_r(NULL,"/", &p_arg); //discard the rest up until '/'
arg = strtok_r(NULL,"?", &p_arg);
printf("arg is now: %s\n", arg); //we got the first operator "test"
if(strncmp(arg, "send", 4) == 0){
while(arg){
if(strncmp(arg,"to",2) == 0){
printf("in to, arg is %s\n", arg);
temp = strtok_r(arg,"to", &p_temp);
temp = strtok_r(temp,"=", &p_temp); //get the number after 'to='
printf("to is %s\n", temp);
} else if(strncmp(arg,"paw",3) == 0){
printf("In paw, arg is %s\n",arg); //got the paw token
//now get the password after the '='
temp = strtok_r(arg,"paw", &p_temp);
temp = strtok_r(temp,"=", &p_temp);
printf("paw is %s\n", temp);
} else if(strncmp(arg,"tz",2) == 0){
printf("In tz, arg is %s\n",arg); //got the tz token
temp = strtok_r(arg,"tz=", &p_temp);
temp = strtok_r(temp," ", &p_temp); //extract tz value
printf("tz is %s\n", temp);
}
arg = strtok_r(NULL,"&", &p_arg);
} //while
} //if "test"
} //main
解决方案
推荐阅读
- android - FCM Android:不允许后台启动
- javascript - 在回调中使用 javascript nodejs 类方法并保留两个上下文
- c++ - 为什么私有继承对象允许成员函数将派生*转换为基*但外部不允许?
- aws-glue - aws 胶水增量加载关系数据库
- java - 如何让我的 GUI 显示符合 JTextFields 的 JLabels?
- exuberant-ctags - Exuberant Ctags 在空 *.ml 文件上产生“文件意外结束”错误
- c++ - 在不使用递归的情况下将 FFT 应用于两个非常大的数的乘法
- jmeter - Blazemeter - 将请求统计转换为秒
- math - Wolfram 函数“Integrate”的原理是什么
- c# - 我的代码不会将我的 CSV 文件读入我的对象列表