#include <stdlib.h>

int len(char *str)
{
    int i;

    i = 0;
    while (str[i] != '\0')
        i++;
    return (i);
}

char    *size_zero(void)
{
    char    *result;

    result = (char *)malloc(1);
    result[0] = '\0';
    return (result);
}

char    *ft_strjoin(int size, char **strs, char *sep)
{
    int     i;
    int     j;
    char    *result;
    int     result_index;

    i = 0;
    result_index = 0;
    if (size <= 0)
        return (size_zero());
    result = (char *)malloc(sizeof(char) * (size + (len(sep) * size) - len(sep))
            + 1);
    if (!result)
        return (NULL);
    while (i < size)
    {
        j = 0;
        while (strs[i][j] != '\0')
            result[result_index++] = strs[i][j++];
        j = 0;
        while (sep[j] != '\0' && i != size - 1)
            result[result_index++] = sep[j++];
        i++;
    }
    result[result_index] = '\0';
    return (result);
}

void test_ft_strjoin(char* test_description, int size, char** strs, char* sep, char* expected) {
    char* result = ft_strjoin(size, strs, sep);
    if (strcmp(result, expected) == 0) {
        printf(COLOR_GREEN "[EX03] PASS: " COLOR_RESET "%s\n", test_description);
    }
    else {
        printf(COLOR_RED "[EX03] FAIL: " COLOR_RESET "%s\n - Expected: '%s'\n - Got:      '%s'\n", test_description, expected, result);
    }
    free(result); 
}


int main(void) {

    // ex03
    const char* test1_strs[] = { "Hello", "world", "this", "is", "C" };
    const char* test1_sep = " ";
    const char* test1_expected = "Hello world this is C";
    test_ft_strjoin("Joining with space separator", 5, test1_strs, test1_sep, test1_expected);

    char* test2_strs[] = { "2024", "07", "17" };
    char* test2_sep = "-";
    char* test2_expected = "2024-07-17";
    test_ft_strjoin("Joining with dash separator", 3, test2_strs, test2_sep, test2_expected);

    char* test3_strs[] = { "One", "Two", "Three" };
    char* test3_sep = "";
    char* test3_expected = "OneTwoThree";
    test_ft_strjoin("Joining with empty separator", 3, test3_strs, test3_sep, test3_expected);

    char* test4_strs[] = {};
    char* test4_sep = ", ";
    char* test4_expected = "";
    test_ft_strjoin("Joining zero strings", 0, test4_strs, test4_sep, test4_expected);

    return 0;
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: