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

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

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

How can I accomplish this in .NET?

14条回答
  •  没有蜡笔的小新
    2020-11-22 17:16

    C# extension method that will do this:

    public static class StringExt
    {
        public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)
        {
             int i = s.IndexOf(oldValue);
             return s.Remove(i, oldValue.Length).Insert(i, newValue);    
        } 
    }
    

    Enjoy

提交回复
热议问题