Split string with delimiters in C

前端 未结 20 1425
你的背包
你的背包 2020-11-21 11:56

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = \"JAN,FEB,MAR,APR,MAY,JUN,JUL,         


        
20条回答
  •  一生所求
    2020-11-21 12:30

    My approach is to scan the string and let the pointers point to every character after the deliminators(and the first character), at the same time assign the appearances of deliminator in string to '\0'.
    First make a copy of original string(since it's constant), then get the number of splits by scan it pass it to pointer parameter len. After that, point the first result pointer to the copy string pointer, then scan the copy string: once encounter a deliminator, assign it to '\0' thus the previous result string is terminated, and point the next result string pointer to the next character pointer.

    char** split(char* a_str, const char a_delim, int* len){
        char* s = (char*)malloc(sizeof(char) * strlen(a_str));
        strcpy(s, a_str);
        char* tmp = a_str;
        int count = 0;
        while (*tmp != '\0'){
            if (*tmp == a_delim) count += 1;
            tmp += 1;
        }
        *len = count;
        char** results = (char**)malloc(count * sizeof(char*));
        results[0] = s;
        int i = 1;
        while (*s!='\0'){
            if (*s == a_delim){
                *s = '\0';
                s += 1;
                results[i++] = s;
            }
            else s += 1;
        }
        return results;
    }
    

提交回复
热议问题