C函数库中的strtok实现

来源:互联网 发布:mac git config 文件 编辑:程序博客网 时间:2024/06/08 08:40
/**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;}

原创粉丝点击