From ca04e8898e191ff91747e245b986d9ce7e9fa480 Mon Sep 17 00:00:00 2001 From: Tilo K Date: Sat, 23 Aug 2025 17:00:04 +0200 Subject: [PATCH] feat: add string concat --- include/tstd/string.h | 9 +++++++++ string.c | 11 +++++++++++ test/test_main.c | 9 +++++++++ 3 files changed, 29 insertions(+) diff --git a/include/tstd/string.h b/include/tstd/string.h index d75de0b..ba0f94f 100644 --- a/include/tstd/string.h +++ b/include/tstd/string.h @@ -63,4 +63,13 @@ void str_to_upper(char* str); */ void str_to_lower(char* str); +/** + * @brief Concatenate two null-terminated strings into a newly allocated string. + * @param str1 First input string (must not be NULL). + * @param str2 Second input string (must not be NULL). + * @return Pointer to a newly allocated null-terminated string containing the concatenated result of str1 and str2. + * Caller is responsible for freeing the allocated memory. + */ +char* str_concat(const char* str1, const char* str2); + #endif //TSTD_STRING_H diff --git a/string.c b/string.c index 222f181..76bfe47 100644 --- a/string.c +++ b/string.c @@ -98,4 +98,15 @@ void str_to_lower(char* str) { str[i] += 'a' - 'A'; } } +} + +char* str_concat(const char* str1, const char* str2) { + const size_t len1 = strlen(str1); + const size_t len2 = strlen(str2); + + char* result = malloc(sizeof(char) * (len1 + len2 + 1)); + memcpy(result, str1, len1); + memcpy(&result[len1], str2, len2); + result[len1 + len2] = '\0'; + return result; } \ No newline at end of file diff --git a/test/test_main.c b/test/test_main.c index ef85ea4..7f68528 100644 --- a/test/test_main.c +++ b/test/test_main.c @@ -94,6 +94,14 @@ int test_string_to_lower() { return 0; } +int test_string_concat() { + char* test_str = str_concat("Hello", "World"); + assert(strcmp(test_str, "HelloWorld") == 0); + free(test_str); + + return 0; +} + int test_string_functions() { int result = 0; @@ -103,6 +111,7 @@ int test_string_functions() { result += test_split_function_by_substring(); result += test_string_to_upper(); result += test_string_to_lower(); + result += test_string_concat(); return result; }