首页 > 解决方案 > 使用 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

标签: cunixstrtok

解决方案


推荐阅读