Add String.trim_left() / right() (#1773)

* Add String.trim_left() / right()

* Fix formatting
This commit is contained in:
Louis Brauer
2025-01-05 21:53:18 +01:00
committed by GitHub
parent f1ef2e8138
commit 35812bd7ba
3 changed files with 55 additions and 4 deletions

View File

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

View File

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

View File

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