How to replace part of string by position?

后端 未结 18 916
逝去的感伤
逝去的感伤 2020-11-28 04:37

I have this string: ABCDEFGHIJ

I need to replace from position 4 to position 5 with the string ZX

It will look like this: ABC

18条回答
  •  生来不讨喜
    2020-11-28 05:13

    If you care about performance, then the thing you want to avoid here are allocations. And if you're on .Net Core 2.1+ (or the, as yet unreleased, .Net Standard 2.1), then you can, by using the string.Create method:

    public static string ReplaceAt(this string str, int index, int length, string replace)
    {
        return string.Create(str.Length - length + replace.Length, (str, index, length, replace),
            (span, state) =>
            {
                state.str.AsSpan().Slice(0, state.index).CopyTo(span);
                state.replace.AsSpan().CopyTo(span.Slice(state.index));
                state.str.AsSpan().Slice(state.index + state.length).CopyTo(span.Slice(state.index + state.replace.Length));
            });
    }
    

    This approach is harder to understand than the alternatives, but it's the only one that will allocate only one object per call: the newly created string.

提交回复
热议问题