feat: add string concat

This commit is contained in:
2025-08-23 17:00:04 +02:00
parent cf8b6765b9
commit ca04e8898e
3 changed files with 29 additions and 0 deletions

View File

@@ -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

View File

@@ -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;
}

View File

@@ -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;
}