How does strtok() split the string into tokens in C?

前端 未结 15 2032
陌清茗
陌清茗 2020-11-22 14:48

Please explain to me the working of strtok() function. The manual says it breaks the string into tokens. I am unable to understand from the manual what it actua

15条回答
  •  野性不改
    2020-11-22 15:40

    Here is my implementation which uses hash table for the delimiter, which means it O(n) instead of O(n^2) (here is a link to the code):

    #include
    #include
    #include
    
    #define DICT_LEN 256
    
    int *create_delim_dict(char *delim)
    {
        int *d = (int*)malloc(sizeof(int)*DICT_LEN);
        memset((void*)d, 0, sizeof(int)*DICT_LEN);
    
        int i;
        for(i=0; i< strlen(delim); i++) {
            d[delim[i]] = 1;
        }
        return d;
    }
    
    
    
    char *my_strtok(char *str, char *delim)
    {
    
        static char *last, *to_free;
        int *deli_dict = create_delim_dict(delim);
    
        if(!deli_dict) {
            /*this check if we allocate and fail the second time with entering this function */
            if(to_free) {
                free(to_free);
            }
            return NULL;
        }
    
        if(str) {
            last = (char*)malloc(strlen(str)+1);
            if(!last) {
                free(deli_dict);
                return NULL;
            }
            to_free = last;
            strcpy(last, str);
        }
    
        while(deli_dict[*last] && *last != '\0') {
            last++;
        }
        str = last;
        if(*last == '\0') {
            free(deli_dict);
            free(to_free);
            deli_dict = NULL;
            to_free = NULL;
            return NULL;
        }
        while (*last != '\0' && !deli_dict[*last]) {
            last++;
        }
    
        *last = '\0';
        last++;
    
        free(deli_dict);
        return str;
    }
    
    int main()
    {
        char * str = "- This, a sample string.";
        char *del = " ,.-";
        char *s = my_strtok(str, del);
        while(s) {
            printf("%s\n", s);
            s = my_strtok(NULL, del);
        }
        return 0;
    }
    

提交回复
热议问题