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