-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Memory
Milestone
Description
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.
runtime/src/libraries/System.Private.Uri/src/System/Uri.cs
Lines 1037 to 1043 in e8b1491
| for (ushort i = 0; i < (ushort)count; ++i) | |
| { | |
| if (result[i] == '/') | |
| { | |
| result[i] = '\\'; | |
| } | |
| } |
runtime/src/libraries/Common/src/System/IO/Archiving.Utils.Windows.cs
Lines 79 to 84 in e8b1491
| 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
gfoidl, PaulusParssinen, MihaZupan, NN---, martincostello and 2 more
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Memory