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

后端 未结 14 1114
忘掉有多难
忘掉有多难 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:15

    One of the overloads of Regex.Replace takes an int for "The maximum number of times the replacement can occur". Obviously, using Regex.Replace for plain text replacement may seem like overkill, but it's certainly concise:

    string output = (new Regex("AA")).Replace(input, "XQ", 1);
    

提交回复
热议问题