strtok改版的代码

C版本自带的strtok函数的作用是对字符串按照分隔符进行分割,然后把每个字符串都显示出来。
但是这里有一个问题,比如:
a||b|c:如果使用C自带的处理的话,直接返回的就是a, b, c;但是我的需求中,需要把中间的空的字符也要取出来,也就是说,’a||b’,在两个分隔符中间没有字母,但是要提示我,而不是直接跳过了。
所以按照我的需求,将strtok进行了修改:

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>

char * sttok_byqiu(char*s, const char* delim, int *flag)
{
    int first_point = 0;
    int secon_point = 0;
    char *token = NULL;
    static char* olds;
    int t;

    //s为空的情况下,说明是继续上面使用
    if(s==NULL && olds != NULL)
    {
        s = olds;
    }
    else if( s != NULL )
        olds = s;
    else
        {
            *flag = -1;
            return NULL;    
        }

    //如果当前的s的第一个字符就是分隔符,说明第一个字符就是空
    // ‘||||b’
    if( *s == *delim )
    {
        *s = '\0';
        token = NULL;
        olds++;
        *flag = 1;
        return token;
    }

    token = s;
    //查找第一个分隔符
    s = strpbrk(token,delim);
    //说明是没有分隔符结尾
    if( s == NULL )
        olds = NULL;//__rawmemchr(token, '\0');
    else
        {
            *s = '\0';
            olds = s+1;
        }
        *flag = 1;
        return token;
}

int main()
{
    char str[] = "1|2|3|||||7";
    char *result = NULL;
    int flag = 0;

    result = sttok_byqiu(str, "|", &flag);
    while( flag == 1 )
    {
        if( result != NULL )
        {
            if( *result != '\0' )
                printf("result = %s\n", result);
            else
                printf("there is null\n");
            printf("--------------------\n");
        }
        else
        {
            printf("there is null\n");
            printf("--------------------\n");
        }

        result = sttok_byqiu(NULL, "|", &flag);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值