C初学者:字符串解析

Eam*_*orr 6 c string parsing

我正在尝试解析以下HTTP响应:

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:15:21 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

??(?????I?O????H????????
                      ?4?@?B?$???S
Run Code Online (Sandbox Code Playgroud)

我想提取"48"和二进制内容.

这是我尝试过的东西:

  //char* str contains the response
  char * pch;
  printf ("Splitting response into tokens:\n");
  pch = strtok (str,"\r\n");
  while (pch != NULL)
  {
      printf ("%s\n",pch);
      pch = strtok (NULL, "\r\n");
  }
Run Code Online (Sandbox Code Playgroud)

但我现在有点卡住......非常感谢任何帮助.


编辑:

这是我做过的事情:

char* pch;
char* pch2;
pch=strstr(buf,"Content-Length:");
pch2=strstr(pch,"\r\n");
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到这两个指针之间的位?


编辑:解决方案:

        char* pch;
        char* pch2;
        pch=strstr(buf,"Content-Length:");
        int i=0;
        char contLen[20];
        for(i=0;i<20;i++){
                char next=pch[strlen("Content-Length:")+i];
                if(next=='\r' || next=='\n'){
                        break;
                }
                contLen[i]=next;
        }
        printf("%d\n",atoi(contLen));
Run Code Online (Sandbox Code Playgroud)

And*_*rsK 6

你为什么不搜索字符串"Content-Length:"呢?然后从那一点开始前进.

您可以使用strstr()查找点str,然后将char指针向前移动strlen("Content-Length:")位置,然后使用读取值atoi()

没有必要将整个字符串标记化