开发者

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 ha开发者_开发知识库d an intuitive and clear way to implement this in C. Thanks!


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).


For example there is such a function in GLib: g_strjoin and g_strjoinv. Probably any bigger library has such functions.

The easiest way is to use such libraries and be happy. It's also not too hard to write this by yourself (look at the other answers). The "big" problem is just that you have to be careful while allocating and freeing those strings. It's C ;-)

Edit: I just see that you used in both examples arrays. So just that you know: g_strjoinv is what you asked for.


I found a function that does this in ANSI C here. I adapted it and added a seperator argument. Make sure to free() the string after using it.

char* join_strings(char* strings[], char* seperator, int count) {
    char* str = NULL;             /* Pointer to the joined strings  */
    size_t total_length = 0;      /* Total length of joined strings */
    int i = 0;                    /* Loop counter                   */

    /* Find total length of joined strings */
    for (i = 0; i < count; i++) total_length += strlen(strings[i]);
    total_length++;     /* For joined string terminator */
    total_length += strlen(seperator) * (count - 1); // for seperators

    str = (char*) malloc(total_length);  /* Allocate memory for joined strings */
    str[0] = '\0';                      /* Empty string we can append to      */

    /* Append all the strings */
    for (i = 0; i < count; i++) {
        strcat(str, strings[i]);
        if (i < (count - 1)) strcat(str, seperator);
    }

    return str;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜