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

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

    As itsmatt said Regex.Replace is a good choice for this however to make his answer more complete I will fill it in with a code sample:

    using System.Text.RegularExpressions;
    ...
    Regex regex = new Regex("foo");
    string result = regex.Replace("foo1 foo2 foo3 foo4", "bar", 1);             
    // result = "bar1 foo2 foo3 foo4"
    

    The third parameter, set to 1 in this case, is the number of occurrences of the regex pattern that you want to replace in the input string from the beginning of the string.

    I was hoping this could be done with a static Regex.Replace overload but unfortunately it appears you need a Regex instance to accomplish it.

提交回复
热议问题