aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJoseph Hunkeler <jhunkeler@gmail.com>2019-12-20 15:56:25 -0500
committerJoseph Hunkeler <jhunkeler@gmail.com>2019-12-20 15:56:25 -0500
commitb34bcc6a1a362f50c73ec93d207f6639d58ad10d (patch)
tree3aa6843ee50cf83066d76cc90e2e955d3cfad4b0 /src
parent76d1132125f9280e0cb430982b74971c53eff450 (diff)
downloadspmc-b34bcc6a1a362f50c73ec93d207f6639d58ad10d.tar.gz
Add join()
Diffstat (limited to 'src')
-rw-r--r--src/strings.c50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/strings.c b/src/strings.c
index 87d2eca..52f81b5 100644
--- a/src/strings.c
+++ b/src/strings.c
@@ -193,6 +193,56 @@ void split_free(char **ptr) {
}
/**
+ * Create new a string from an array of strings
+ *
+ * ~~~{.c}
+ * char *array[] = {
+ * "this",
+ * "is",
+ * "a",
+ * "test",
+ * NULL,
+ * }
+ *
+ * char *test = join(array, " "); // "this is a test"
+ * char *test2 = join(array, "_"); // "this_is_a_test"
+ * char *test3 = join(array, ", "); // "this, is, a, test"
+ *
+ * free(test);
+ * free(test2);
+ * free(test3);
+ * ~~~
+ *
+ * @param arr
+ * @param separator characters to insert between elements in string
+ * @return new joined string
+ */
+char *join(char **arr, const char *separator) {
+ char *result = NULL;
+ int records = 0;
+ size_t total_bytes = 0;
+
+ if (!arr) {
+ return NULL;
+ }
+
+ for (int i = 0; arr[i] != NULL; i++) {
+ total_bytes += strlen(arr[i]);
+ records++;
+ }
+ total_bytes += records * (strlen(separator) + 1);
+
+ result = (char *)calloc(total_bytes, sizeof(char));
+ for (int i = 0; i < records; i++) {
+ strcat(result, arr[i]);
+ if (i < (records - 1)) {
+ strcat(result, separator);
+ }
+ }
+ return result;
+}
+
+/**
* Extract the string encapsulated by characters listed in `delims`
*
* ~~~{.c}