mirror of
https://github.com/Tilo-K/tstd.git
synced 2026-01-10 23:11:00 +00:00
feat: add str trim
This commit is contained in:
@@ -72,4 +72,12 @@ void str_to_lower(char* str);
|
|||||||
*/
|
*/
|
||||||
char* str_concat(const char* str1, const char* str2);
|
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
|
#endif //TSTD_STRING_H
|
||||||
|
|||||||
21
string.c
21
string.c
@@ -109,4 +109,25 @@ char* str_concat(const char* str1, const char* str2) {
|
|||||||
memcpy(&result[len1], str2, len2);
|
memcpy(&result[len1], str2, len2);
|
||||||
result[len1 + len2] = '\0';
|
result[len1 + len2] = '\0';
|
||||||
return result;
|
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;
|
||||||
}
|
}
|
||||||
@@ -102,6 +102,16 @@ int test_string_concat() {
|
|||||||
return 0;
|
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 test_string_functions() {
|
||||||
int result = 0;
|
int result = 0;
|
||||||
|
|
||||||
@@ -112,6 +122,7 @@ int test_string_functions() {
|
|||||||
result += test_string_to_upper();
|
result += test_string_to_upper();
|
||||||
result += test_string_to_lower();
|
result += test_string_to_lower();
|
||||||
result += test_string_concat();
|
result += test_string_concat();
|
||||||
|
result += test_trim();
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user