From 6505e3ba490bfd2c8d78795701644c1e5f4edb30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20LUDWIG?= Date: Wed, 9 Aug 2023 20:21:33 +0200 Subject: [PATCH] feat: add `string_remove_character` --- lib/string.c | 14 ++++++++++++++ lib/string.h | 11 +++++++++++ test/string_test.c | 8 ++++++++ test/string_test.h | 2 ++ 4 files changed, 35 insertions(+) diff --git a/lib/string.c b/lib/string.c index 258176d..730750c 100644 --- a/lib/string.c +++ b/lib/string.c @@ -37,6 +37,20 @@ void string_replace(string_t string, char search, char replace) { string[string_length] = '\0'; } +void string_remove_character(char* string, char search) { + size_t string_length = string_get_length(string); + for (size_t index = 0; index < string_length; index++) { + if (string[index] == search) { + for (size_t index_string = index; index_string < string_length; index_string++) { + string[index_string] = string[index_string + 1]; + } + string_length--; + index--; + } + } + string[string_length] = '\0'; +} + void string_trim_start(string_t string, char character) { size_t string_length = string_get_length(string); size_t index_space = 0; diff --git a/lib/string.h b/lib/string.h index 3b241bd..7bdc2cf 100644 --- a/lib/string.h +++ b/lib/string.h @@ -51,6 +51,17 @@ void string_to_lowercase(string_t string); */ void string_replace(string_t string, char search, char replace); +/** + * @brief Removes all the occurrences of a character in a string. + * + * NOTE: Mutates the string. + * + * @param string + * @param search A character search value. + * @since v4.1.0 + */ +void string_remove_character(char* string, char search); + /** * @brief Removes all `character` from the start of a string. * diff --git a/test/string_test.c b/test/string_test.c index 47c8444..fc7ba75 100644 --- a/test/string_test.c +++ b/test/string_test.c @@ -5,6 +5,7 @@ void string_test() { string_to_uppercase_test(); string_to_lowercase_test(); string_replace_test(); + string_remove_character_test(); string_trim_start_test(); string_trim_end_test(); string_trim_test(); @@ -54,6 +55,13 @@ void string_replace_test() { free(string); } +void string_remove_character_test() { + string_t string = string_copy("hello world"); + string_remove_character(string, 'l'); + assert(assert_string_equal(string, "heo word")); + free(string); +} + void string_trim_start_test() { string_t string = string_copy(" hello world "); string_trim_start(string, ' '); diff --git a/test/string_test.h b/test/string_test.h index 871c06f..d453258 100644 --- a/test/string_test.h +++ b/test/string_test.h @@ -18,6 +18,8 @@ void string_to_lowercase_test(); void string_replace_test(); +void string_remove_character_test(); + void string_trim_start_test(); void string_trim_end_test();