cc-strings

join() or implode() in C


One thing I love about Python and PHP is the ability to make a string from array easily:

Python: ', '.join(['a', 'b', 'c'])
PHP: implode(', ', array('a', 'b', 'c'));

However, I was wondering if anybody had an intuitive and clear way to implement this in C. Thanks!


Solution

  • Sure, there are ways - just nothing built-in. Many C utility libraries have functions for this - eg, glib's g_strjoinv. You can also roll your own, for example:

    static char *util_cat(char *dest, char *end, const char *str)
    {
        while (dest < end && *str)
            *dest++ = *str++;
        return dest;
    }
    
    size_t join_str(char *out_string, size_t out_bufsz, const char *delim, char **chararr)
    {
        char *ptr = out_string;
        char *strend = out_string + out_bufsz;
        while (ptr < strend && *chararr)
        {
            ptr = util_cat(ptr, strend, *chararr);
            chararr++;
            if (*chararr)
                ptr = util_cat(ptr, strend, delim);
        }
        return ptr - out_string;
    }
    

    The main reason it's not built in is because the C standard library is very minimal; they wanted to make it easy to make new implementations of C, so you don't find as many utility functions. There's also the problem that C doesn't give you many guidelines about how to, for example, decide how many elements are in arrays (I used a NULL-array-element terminator convention in the example above).