Home > Software design >  split string with delimiters taking into account ' " ' in C
split string with delimiters taking into account ' " ' in C

Time:05-11

How do I write a fonction that splint a string taking as a delimiter but taking into account that something into " must be considerating as one thing:

exemple :

input :

char *input = "./display \"hello world\" hello everyone";
char **output = split(input);

output :

output[0] = ./display
output[1] = hello world
output[2] = hello
output[3] = everyone
output[4] = NULL

CodePudding user response:

I wouldn't vouch for this, nor run it without a lot more thought and some testing as there are undoubtedly edge case that are missed, but a quick and dirty solution might look like:

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


struct string_array {
    char **data;
    size_t cap;
    size_t len;
};

void
append(struct string_array *v, char *s)
{
    while( v->cap <= v->len ){
        v->cap  = 128;
        v->data = realloc(v->data, v->cap * sizeof *v->data);
        if( v->data == NULL ){
            perror("malloc");
            exit(EXIT_FAILURE);
        }
    }
    v->data[v->len  ] = s;
}

char **
split(char *input)
{
    struct string_array v = {NULL, 0, 0};
    char *t = input;
    while( *t ){
        int q = *t == '"';
        char *e = q   t   strcspn(t   q, q ? "\"" : " \"\t\n");
        append(&v, t   q);
        t = (*e == '"')   e   strspn(e   (*e == '"'), " \"\t\n");
        *e = '\0';
    }
    append(&v, NULL);
    return v.data;
}

int
main(int argc, char **argv)
{
    char *input = strdup(argc > 1 ? argv[1] :
        "./display \"hello world\" hello everyone");
    char **output = split(input);
    for( char **t = output; *t; t  = 1 ){
        printf("%ld: '%s'\n", t - output, *t);
    }
}
  • Related