c语言实现split函数。用于http协议字符串解析比较有用。用\r\n分隔成不同的数组。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char **str;     //the PChar of string array
    size_t num;     //the number of string
}IString;


/** \Split string by a char
 *
 * \param  src:the string that you want to split
 * \param  delim:split string by this char
 * \param  istr:a srtuct to save string-array's PChar and string's amount.
 * \return  whether or not to split string successfully
 *
 */
int Split(char *src, char *delim, IString* istr)//split buf
{
    int i;
    char *str = NULL, *p = NULL;

    (*istr).num = 1;
    str = (char*)calloc(strlen(src)+1,sizeof(char));
    if (str == NULL) return 0;
    (*istr).str = (char**)calloc(1,sizeof(char *));
    if ((*istr).str == NULL) return 0;
    strcpy(str,src);

    p = strtok(str, delim);
    (*istr).str[0] = (char*)calloc(strlen(p)+1,sizeof(char));
    if ((*istr).str[0] == NULL) return 0;
    strcpy((*istr).str[0],p);
    for(i=1; p = strtok(NULL, delim); i++)
    {
        (*istr).num++;
        (*istr).str = (char**)realloc((*istr).str,(i+1)*sizeof(char *));
        if ((*istr).str == NULL) return 0;
        (*istr).str[i] = (char*)calloc(strlen(p)+1,sizeof(char));
        if ((*istr).str[0] == NULL) return 0;
        strcpy((*istr).str[i],p);
    }
    free(str);
    str = p = NULL;

    return 1;
}




int main()
{
    int i;
    char s[]="data0\r\ndata1\r\ndata2\r\ndata3\r\ndata4\r\ndata5\r\ndata6\r\ndata7\r\ndata8";
    IString istr;

    if (  Split(s,"||",&istr) )
    {
        for (i=0;i<istr.num;i++)
            printf("%s\n",istr.str[i]);
        //when you don't ues it,you must to free memory.
        for (i=0;i<istr.num;i++)
            free(istr.str[i]);
        free(istr.str);
    }
    else
        printf("memory allocation failure!\n");


    system("pause");
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值