How do I replace the *first instance* of a string in .NET?

后端 未结 14 1073
忘掉有多难
忘掉有多难 2020-11-22 16:41

I want to replace the first occurrence in a given string.

How can I accomplish this in .NET?

14条回答
  •  萌比男神i
    2020-11-22 17:00

    Updated extension method utilizing Span to minimize new string creation

        public static string ReplaceFirstOccurrence(this string source, string search, string replace) {
            int index = source.IndexOf(search);
            if (index < 0) return source;
            var sourceSpan = source.AsSpan();
            return string.Concat(sourceSpan.Slice(0, index), replace, sourceSpan.Slice(index + search.Length));
        }
    

提交回复
热议问题