C函数库中的strtok实现

/*
*copyright@nciaebupt 转载请注明出处
*原型:char *strtok(char *str, char *delimiters);
*用法:#include <string.h>
*功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。
*说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。
*   strtok在s中查找包含在delim中的字符并用NULL('\0')来替换,
*   直到找遍整个字符串。返回指向下一个标记串。当没有标记串时则返回空字符NULL。
*使用C函数库中的strtok
*/
#include <cstdio>
#include <cstring>

int main(int args,char ** argv)
{
    char str[] = "- This, is a sample string.";
    char *pch;
    printf("split sentence '%s' into tokens : \n",str);
    pch = strtok(str,"-,. ");
    while(pch != NULL)
    {
        printf("%s\n",pch);
        pch = strtok(NULL,"-,. ");
    }
    getchar();
    return 0;
}

/*
*copyright@nciaebupt 转载请注明出处
*原型:char *strtok(char *str, char *delimiters);
*用法:#include <string.h>
*功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。
*说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。
*   strtok在s中查找包含在delim中的字符并用NULL('\0')来替换,
*   直到找遍整个字符串。返回指向下一个标记串。当没有标记串时则返回空字符NULL。
*自己实现strtok
*/
#include <cstdio>
#include <cstring>

char * _strtok(char * string,const char * control)
{
    unsigned char * str = NULL;
    const unsigned char * ctrl = (const unsigned char *)control;
    unsigned char map[32];
    int count;
    static char * nextoken;
    /*clear the control map*/
    memset(map,0,32*sizeof(unsigned char));
    /*set bits in control map*/
    while(*ctrl)
    {
        map[*ctrl >> 3] |= (0x01 << (*ctrl & 7));
        ctrl++;
    }
    /*set the str if string is NULL the str = nextoken else str = string*/
    if(string)
        str = (unsigned char *)string;
    else
        str = (unsigned char *)nextoken;
    /*find beginning of token*/
    while((map[*str >> 3] & (0x01 << (*str & 7))) && *str)
        str++;
    /*remember the beginning of the token*/
    string = (char *)str;
    /*find the end of the token,set the last of the token '\0'*/
    for(;*str;str++)
    {
        if(map[*str >> 3] & (0x01 << (*str & 7)))
        {
            *str++ = '\0';
            break;
        }
    }
    /*remember the rest of the string*/
    nextoken = (char *)str;
    /*return the result*/
    if((unsigned char *)string == str)
        return NULL;
    else
        return string;
}

int main(int args,char ** argv)
{
    char str[] = "- This, is a sample string.";
    char *pch;
    printf("split sentence '%s' into tokens : \n",str);
    pch = _strtok(str,"-,. ");
    while(pch != NULL)
    {
        printf("%s\n",pch);
        pch = _strtok(NULL,"-,. ");
    }
    getchar();
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值