On 10.08.2010 00:29, simendsjo wrote:
Replacing with "" / null is missing.
I first looked at the function and modified it. Quickly noticed that a
few unit tests were missing:
assert(replace("foo", "foo", "") == "");
assert(replace("foo", "foo", null) == "");
I refactored replace to understand what was going on (related to my post
"is this more readable").
I've seen a couple of functions using Appender, and it's documentation
says it's faster than ~=. I tried to change char[] result to Appender,
but dmd crashed...
string replace(string s, string from, string to)
{
if (from.length == 0) // Nothing to replace
return s;
char[] result;
for (size_t searchIndex; searchIndex < s.length; )
{
auto rest = s[searchIndex .. s.length];
auto fromIndex = indexOf(rest, from);
bool nothingToReplace = (fromIndex == -1);
if (nothingToReplace)
{
bool firstSearch = (searchIndex == 0);
if (firstSearch)
{
// Never found, so just return s
return s;
}
result ~= rest;
break;
}
auto beforeFrom = s[searchIndex .. searchIndex + fromIndex];
result ~= beforeFrom;
result ~= to;
searchIndex += fromIndex + from.length;
}
return assumeUnique(result);
}