Split string with delimiters in C

前端 未结 20 1439
你的背包
你的背包 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:04

    My version:

    int split(char* str, const char delimeter, char*** args) {
        int cnt = 1;
        char* t = str;
    
        while (*t == delimeter) t++;
    
        char* t2 = t;
        while (*(t2++))
            if (*t2 == delimeter && *(t2 + 1) != delimeter && *(t2 + 1) != 0) cnt++;
    
        (*args) = malloc(sizeof(char*) * cnt);
    
        for(int i = 0; i < cnt; i++) {
            char* ts = t;
            while (*t != delimeter && *t != 0) t++;
    
            int len = (t - ts + 1);
            (*args)[i] = malloc(sizeof(char) * len);
            memcpy((*args)[i], ts, sizeof(char) * (len - 1));
            (*args)[i][len - 1] = 0;
    
            while (*t == delimeter) t++;
        }
    
        return cnt;
    }
    

提交回复
热议问题