Join () or implode () in C

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

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

However, I was wondering if anyone has an intuitive and clear way to implement this in C. Thank you!

+4
source share
3 answers

Of course, there are ways - just nothing is built in. Many C utility libraries have functions for this β€” for example, glib g_strjoinv . You can also flip 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 is not built-in is because the standard C library is very minimal; they wanted to simplify the creation of new C implementations, so you won’t find so many useful features. There is also a problem that C does not give you many recommendations on how, for example, to decide how many elements are in arrays (I used the terminator convention of NULL array elements in the above example).

+9
source

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

The easiest way is to use such libraries and be happy. It is also not so difficult to write it yourself (look at other answers). The "big" problem is that you have to be careful when allocating and freeing these lines. This is C; -)

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

+5
source

I found a function that does this in ANSI C here . I adapted it and added the seperator argument. Be sure to free () the line 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; } 
+4
source

Source: https://habr.com/ru/post/1335410/


All Articles