How to split a string on multiple single‑character delimiters (and keep them) in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** split_keep_delims(const char* s, const char* delims, int* out_count) {
    int capacity = 16;
    int count = 0;
    char** result = malloc(capacity * sizeof(char*));

    const char* p = s;
    char buffer[1024];
    int buf_i = 0;

    while (*p) {
        if (strchr(delims, *p)) {
            if (buf_i > 0) {
                buffer[buf_i] = '\0';
                result[count++] = strdup(buffer);
                buf_i = 0;
            }
            char d[2] = {*p, '\0'};
            result[count++] = strdup(d);
        } else {
            buffer[buf_i++] = *p;
        }
        p++;

        if (count >= capacity) {
            capacity *= 2;
            result = realloc(result, capacity * sizeof(char*));
        }
    }

    if (buf_i > 0) {
        buffer[buf_i] = '\0';
        result[count++] = strdup(buffer);
    }

    *out_count = count;
    
    return result;
}

int main() {
    const char* s = "aa,bbb;cccc|ddddd";
    int n;
    
    char** parts = split_keep_delims(s, ",;|", &n);

    for (int i = 0; i < n; i++) {
        printf("[%s] ", parts[i]);
        free(parts[i]);
    }

    free(parts);
}



/*

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...