基于memcached中命令分析函数tokenize_command改造的split函数

今天使用C重构php代码,需要手写一个split函数,于是就模仿memcached中获取用户命令的函数

static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens)

写了一个简单的split函数:

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

typedef struct node {
    char *value;
    struct node *next;
}Node;


/**
 * 字符串切割函数
 * pattern 字符参数      切割符参数,分隔字符串所使用的参数
 * str     字符串参数    被分切割的字符串
 * data    链表      用于存储切割完的字符串
 * 失败    返回 1
 * 成功    返回 0
 */
Node *split(char pattern,char *str)
{
    if(!pattern || (strlen(str) <= 0)) return NULL;
    char *e,*s;
    Node *data,*p,*tail;
    unsigned int i,len = strlen(str);
    e = s = str;
    data = (Node *)malloc(sizeof(Node));
    tail = data;
    tail->next = NULL;
    tail->value = "";

    for(i = 0;i<len;i++)
    {
        if(*e == pattern)
        {
            if(s != e)
            {
                p=(Node *)malloc(sizeof(Node));
                p->value = s;
                p->next = NULL;

                tail->next = p;
                tail = p;

                *e = '\0';
                if(e == (str + len - 1))
                {
                    e++;
                    s = e;
                    break;
                }

            }
            s = e+1;
        }
        e++;
    }

    if(s != e)
    {

        p=(Node *)malloc(sizeof(Node));
        p->value = s;
        p->next = NULL;
        tail->next=p;
        tail=p;
    }
    return data;
}

好多年没有写过C了,基本上还停留在当初大学毕业的水平,呵呵。

 

posted @ 2015-04-10 17:55  lrxing  阅读(266)  评论(0编辑  收藏  举报