diff --git a/include/tstd/string.h b/include/tstd/string.h index ba0f94f..6db16ed 100644 --- a/include/tstd/string.h +++ b/include/tstd/string.h @@ -72,4 +72,12 @@ void str_to_lower(char* str); */ char* str_concat(const char* str1, const char* str2); +/** + * @brief Trim leading and trailing whitespace characters from a string. + * @param str Null-terminated input string (must not be NULL). + * @return A newly allocated string with leading and trailing whitespace removed. + * The caller is responsible for freeing the allocated memory. + */ +char* str_trim(const char* str); + #endif //TSTD_STRING_H diff --git a/string.c b/string.c index 76bfe47..ff3bd3c 100644 --- a/string.c +++ b/string.c @@ -109,4 +109,25 @@ char* str_concat(const char* str1, const char* str2) { memcpy(&result[len1], str2, len2); result[len1 + len2] = '\0'; return result; +} + +bool p_str_char_is_rubbish(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; +} + +char* str_trim(const char* str) { + size_t start = 0; + size_t end = strlen(str) - 1; + while (p_str_char_is_rubbish(str[start])) { + start++; + } + while (p_str_char_is_rubbish(str[end])) { + end--; + } + + char* new_str = malloc(sizeof(char) * (end - start + 2)); + memcpy(new_str, &str[start], end - start + 1); + new_str[end-start+1] = '\0'; + + return new_str; } \ No newline at end of file diff --git a/test/test_main.c b/test/test_main.c index 7f68528..9f048c9 100644 --- a/test/test_main.c +++ b/test/test_main.c @@ -102,6 +102,16 @@ int test_string_concat() { return 0; } +int test_trim() { + char* test_str = " Hello, test. test "; + char* trimmed_str = str_trim(test_str); + + assert(strcmp(trimmed_str, "Hello, test. test") == 0); + free(trimmed_str); + + return 0; +} + int test_string_functions() { int result = 0; @@ -112,6 +122,7 @@ int test_string_functions() { result += test_string_to_upper(); result += test_string_to_lower(); result += test_string_concat(); + result += test_trim(); return result; }