c - C中将字符串拆分为多个子字符串

标签 c windows char

我有一个包含多个 HTTP header 的字符。 现在我想拆分 header 并将每个 header 存储到 char[] 数组中,例如

myheader[0] = "POST /index001.html HTTP/1.1\r\nHost:xxx  ...";   
myheader[1] = "POST /index002.html HTTP/1.1\r\nHost:xxx  ..."   

每个 header 大小都不同,因此我无法计算字节数。我不知道该怎么做。 strstr() 只查找第一个子字符串。

缓冲区格式如下:

POST /index001.html HTTP/1.1
Host: xxx
...
POST /index002.html HTTP/1.1
Host: xxx
...
POST /index003.html HTTP/1.1
Host: xxx
...

谁能帮我写一下代码吗?

编辑:

我编写了一个从缓冲区中提取子字符串的函数。但它只能处理第一对“POST”。 例如,

GetInBetween( "1234www567890rrr777wwwOUEJF99rrr", "www", "rrr") 只能获取“567890”。

char * GetInBetween( char* buffer, char* start, char* end)
{
    char * subbuffer = NULL;
    subbuffer = strstr(buffer, startpoint);  

    int betweenLen = 0;
    if (subbuffer == NULL)
    {
        return NULL;
    }
    betweenLen = strcspn(subbuffer, endpoint );   

    int sbLen=0;
    sbLen= strlen(subbuffer);   
    int spLen =0;
    spLen = strlen(startpoint);  

    int dataLen =0;
    dataLen = betweenLen - spLen;  

    char databuffer[1024];
    for (int i =0; i< dataLen; i++) 
    {
        databuffer[0+i] = subbuffer[4+i]; 
    }
    databuffer[dataLen] ='\0';
    int test = strlen(databuffer);

    return databuffer;
}

最佳答案

您可以更改函数以保留一些早期调用的内存,就像 strtok 所做的那样。然后,您可以在同一缓冲区中重复调用函数以查找任何后续出现的情况。作为这种方法的草图(自己完成):

char * GetInBetween( char* buffer, char* startstr, char* endstr)
{
    static char *lastbuf, *lastbufp, *laststartstr, *lastendstr;
    char * subbuffer = NULL;
    if (startstr==NULL || endstr==NULL) {
        if (lastbuf!=buffer) return NULL;    // not same buffer: error;
        if (lastbufp==NULL) return NULL;     // no previous match, so no next match
        subbuffer= strstr(lastbufp, laststartstr);
    }
    else
    {
        laststartstr= startstr;        // remember the parts to search in between
        lastendstr= endstr;
        lastbuf= buffer;
        subbuffer = strstr(buffer, startpoint); 
        lastbufp= NULL;                // no match yet to remember
    }

关于c - C中将字符串拆分为多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775847/

相关文章:

c - 如何在没有 Visual Studio 的情况下为 Windows 编写内核驱动程序?

c - 使用 C 将 char 添加到字符串文字

c - 检查有效 Unix FTP 命令的程序(不工作)

c - 这是 C99 标准明确定义的吗?

c - 子进程中fork()后泄漏,为什么?

c++ - MinGW 应用程序的崩溃报告

c - c中全局变量和堆变量有什么异同?

windows - 如何在窗外画画?

C 打印一个没有值(value)的字符

c - 动态向 char * 添加单词