KEMBAR78
[API Proposal]: MemoryExtensions.Replace(Span<T>, T, T) · Issue #75322 · dotnet/runtime · GitHub
Skip to content

[API Proposal]: MemoryExtensions.Replace(Span<T>, T, T) #75322

@stephentoub

Description

@stephentoub

Background and motivation

string.Replace(char, char) is useful for replacing every occurrence of a character value. When using spans/arrays to build up strings, that capability is also useful, but today it needs to be hand-rolled, e.g.

Span<char> tmp = ...;
int pos;
while ((pos = tmp.IndexOf(oldValue)) >= 0)
{
    tmp[pos] = newValue;
    tmp = tmp.Slice(pos + 1);
}

It'd be good to have this as a reusable helper on MemoryExtensions so that such open-coded loops can be replaced. There are other more complicated variations of this as well, but this is a simple and common one we can include.

e.g.

for (ushort i = 0; i < (ushort)count; ++i)
{
if (result[i] == '/')
{
result[i] = '\\';
}
}

int pos;
while ((pos = dest.IndexOf('\\')) >= 0)
{
dest[pos] = '/';
dest = dest.Slice(pos + 1);
}

API Proposal

namespace System
{
    public static class MemoryExtensions
    {
+        public static void Replace<T>(this Span<T> span, T oldValue, T newValue) where T : IEquatable<T>?;
    }
}

API Usage

char[] result = ...;
result.AsSpan().Replace('\\', '/');
return new string(result);

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions