How to write an equivalent to PHP implode(string $separator, array $array): string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* implode(const char* separator, const char* elements[], size_t count) {
    if (count == 0) return strdup("");  // empty array == empty string

    size_t sep_len = strlen(separator);
    size_t total_len = 0;

    // Calculate total length needed
    for (size_t i = 0; i < count; i++) {
        total_len += strlen(elements[i]);
        if (i < count - 1) total_len += sep_len;
    }

    // Allocate buffer (+1 for null terminator)
    char* result = malloc(total_len + 1);
    if (!result) return NULL;  // allocation failed

    result[0] = '\0';  // start with empty string

    // Concatenate elements with separator
    for (size_t i = 0; i < count; i++) {
        strcat(result, elements[i]);
        if (i < count - 1) strcat(result, separator);
    }

    return result;
}

int main(void) {
    const char* words[] = {"May", "the", "Force", "be", "with", "you"};
    size_t count = sizeof(words) / sizeof(words[0]);

    char* result = implode("-", words, count);
    if (result) {
        printf("%s\n", result);  
        free(result);            // free allocated memory
    }

    return 0;
}


/*
run:

May-the-Force-be-with-you

*/

 



answered Dec 5, 2025 by avibootz

Related questions

...