Skip to content

Instantly share code, notes, and snippets.

@nbulischeck
Created February 26, 2018 03:52

Revisions

  1. nbulischeck created this gist Feb 26, 2018.
    65 changes: 65 additions & 0 deletions partition.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    struct view { const char *s; size_t len; };

    size_t partition(struct view *result, size_t n,
    const char *str, const char *delim){
    char *startp = (char *)str, *endp;
    size_t l = strlen(delim), i = 0;

    while ((endp = strstr(startp, delim)) && (i < n)){
    size_t diff = endp - startp;
    if (diff){
    (result+i)->s = startp;
    (result+i++)->len = diff;
    }
    startp = endp + l;
    }

    if ((*startp) && (i < n)){
    (result+i)->s = startp;
    (result+i++)->len = strlen(startp);
    }

    return (i > n) ? n : i;
    }

    char **instantiate(struct view *result, size_t size){
    int i;
    char **strings = malloc((size+1) * sizeof(char *));
    for (i = 0; i < size; i++){
    strings[i] = malloc(((result+i)->len+1) * sizeof(char));
    strncpy(strings[i], (result+i)->s, (result+i)->len);
    strings[i][(result+i)->len] = '\0';
    }
    strings[size] = NULL;
    return strings;
    }

    void destroy(char **args){
    int i = 0;
    while (args[i]){
    free(args[i++]);
    } free(args);
    }

    int main(){
    int i = 0;
    size_t n = 1024, ret = 0;
    char **strings;
    struct view *result = malloc(n * sizeof(struct view));

    ret = partition(result, n, "foobarfoobarfoobarfoobar", "foo");
    strings = instantiate(result, ret);

    for (i = 0; i < ret; i++){
    printf("%s\n", strings[i]);
    }

    destroy(strings);

    free(result);
    return 0;
    }