Add replace and treplace to String (#2127)

* Add replace and treplace functions to String
This commit is contained in:
DragonFriend
2025-05-14 04:00:20 -05:00
committed by GitHub
parent abe4727c3a
commit 50b4d7aa35
4 changed files with 57 additions and 2 deletions

View File

@@ -278,7 +278,6 @@ macro enum_by_name($Type, String enum_name) @builtin
*>
macro @enum_from_value($Type, #value, value) @builtin
{
usz elements = $Type.elements;
foreach (e : $Type.values)
{
if (e.#value == value) return e;

View File

@@ -154,6 +154,39 @@ fn String join(Allocator allocator, String[] s, String joiner)
};
}
<*
Replace all instances of one substring with a different string.
@param [in] self
@param [in] needle : `The string to be replaced`
@param [in] new_str : `The replacement string`
@param [&inout] allocator : `The allocator to use for the String`
@return "The new string with the elements replaced"
*>
fn String String.replace(self, Allocator allocator, String needle, String new_str) @nodiscard
{
@pool()
{
String[] split = self.tsplit(needle);
return dstring::join(tmem, split, new_str).copy_str(mem);
};
}
<*
Replace all instances of one substring with a different string, allocating the new string on the temp allocator.
@param [in] self
@param [in] needle : `The string to be replaced`
@param [in] new_str : `The replacement string`
@return "The new string with the elements replaced"
*>
fn String String.treplace(self, String needle, String new_str)
{
String[] split = self.tsplit(needle);
return dstring::join(tmem, split, new_str).str_view();
}
<*
Remove characters from the front and end of a string.