diff --git a/lib/std/core/string.c3 b/lib/std/core/string.c3 index 158aa67a9..bb8dc5ce2 100644 --- a/lib/std/core/string.c3 +++ b/lib/std/core/string.c3 @@ -145,14 +145,40 @@ fn String join_new(String[] s, String joiner, Allocator allocator = allocator::h @return `a substring of the string passed in` *> fn String String.trim(string, String to_trim = "\t\n\r ") +{ + return string.trim_left(to_trim).trim_right(to_trim); +} + +<* + Remove characters from the front of a string. + + @param [in] string `The string to trim` + @param [in] to_trim `The set of characters to trim, defaults to whitespace` + @pure + @return `a substring of the string passed in` +*> +fn String String.trim_left(string, String to_trim = "\t\n\r ") { usz start = 0; usz len = string.len; while (start < len && char_in_set(string[start], to_trim)) start++; if (start == len) return string[:0]; - usz end = len - 1; - while (end > start && char_in_set(string[end], to_trim)) end--; - return string[start..end]; + return string[start..]; +} + +<* + Remove characters from the end of a string. + + @param [in] string `The string to trim` + @param [in] to_trim `The set of characters to trim, defaults to whitespace` + @pure + @return `a substring of the string passed in` +*> +fn String String.trim_right(string, String to_trim = "\t\n\r ") +{ + usz len = string.len; + while (len > 0 && char_in_set(string[len - 1], to_trim)) len--; + return string[:len]; } <* diff --git a/releasenotes.md b/releasenotes.md index fe6cbd767..fb031669d 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -70,6 +70,7 @@ - Updated hash function. - Added URL parser. - Added convenience functions to `Maybe`. +- Added `String.trim_left()` and `.trim_right()`. ## 0.6.5 Change list diff --git a/test/unit/stdlib/core/string.c3 b/test/unit/stdlib/core/string.c3 index fe1fc88eb..ea9cab00e 100644 --- a/test/unit/stdlib/core/string.c3 +++ b/test/unit/stdlib/core/string.c3 @@ -59,6 +59,7 @@ fn void test_ends_with() assert(s.ends_with("")); assert(!s.ends_with("e")); } + fn void test_trim() { String s = " \t\nabc "; @@ -67,6 +68,29 @@ fn void test_trim() assert(" \n\tok".trim() == "ok"); assert("!! \n\t ".trim() == "!!"); assert(s.trim("c \t") == "\nab"); + assert("".trim() == ""); + + +} + +fn void test_trim_left() +{ + String s = " \t\nabc "; + assert(s.trim_left() == "abc "); + assert("\n\t".trim_left() == ""); + assert(" \n\tok".trim_left() == "ok"); + assert("!! \n\t ".trim_left() == "!! \n\t "); + assert("".trim_left() == ""); +} + +fn void test_trim_right() +{ + String s = " \t\nabc "; + assert(s.trim_right() == " \t\nabc"); + assert("\n\t".trim_right() == ""); + assert(" \n\tok".trim_right() == " \n\tok"); + assert("!! \n\t ".trim_right() == "!!"); + assert("".trim_right() == ""); } fn void test_split() @@ -175,4 +199,4 @@ fn void! test_hex_conversion() { assert("0x123aCd".to_long()! == 0x123acd); assert("123acD".to_long(16)! == 0x123acd); -} \ No newline at end of file +}