DinoMage on Twitter RSS Feed
2
Apr

C string explode

   Posted by: in Dev, Libraries

I was working on porting some code from C++ to C and I couldn’t really find a simple explode() function for C online.  So, of course, I had to make it myself.  I’m just putting it here for general reference.  This implementation uses malloc(), so it’s going to be a little less performant than a static one, though easier to use.  At least it can’t be any worse than my C++ implementation!

No guarantees, you’re granted the code under the MIT license.

typedef struct StringList
{
    char* value;
    struct StringList* next;
} StringList;
void StringListFree(StringList* node)
{
    // Delete the nodes in order
    while(node != NULL)
    {
        StringList* last = node;
        node = node->next;
        free(last->value);
        free(last);
    }
}
// Returns a linked list of malloc'ed NULL-terminated strings.  The delimiter is erased.
static StringList* explode(const char* text, char delimiter)
{
    StringList* head;
    StringList* new_node;
    StringList** node;
    const char* start;
    const char* end;
    unsigned int size;
    if(text == NULL)
        return NULL;
    head = NULL;
    node = &head;
    // Doesn't technically support UTF-8, but it's probably fine, right?
    size = 0;
    start = end = text;
    while(1)
    {
        if(*end == delimiter || *end == '\0')
        {
            *node = (StringList*)malloc(sizeof(StringList));
            new_node = *node;
            new_node->value = (char*)malloc(size + 1);
            memcpy(new_node->value, start, size);
            new_node->value[size] = '\0';
            new_node->next = NULL;
            if(*end == '\0')
                break;
            node = &((*node)->next);
            start = end+1;
            size = 0;
        }
        else
            ++size;
        ++end;
    }
    return head;
}

Leave a Reply