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

后端 未结 14 959
忘掉有多难
忘掉有多难 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 16:52
    using System.Text.RegularExpressions;
    
    RegEx MyRegEx = new RegEx("F");
    string result = MyRegex.Replace(InputString, "R", 1);
    

    will find first F in InputString and replace it with R.

    0 讨论(0)
  • 2020-11-22 16:58

    And because there is also VB.NET to consider, I would like to offer up:

    Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String
        Dim pos As Integer = text.IndexOf(search)
        If pos >= 0 Then
            Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
        End If
        Return text 
    End Function
    
    0 讨论(0)
  • 2020-11-22 16:59

    Take a look at Regex.Replace.

    0 讨论(0)
  • 2020-11-22 16:59

    In C# syntax:

    int loc = original.IndexOf(oldValue);
    if( loc < 0 ) {
        return original;
    }
    return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
    
    0 讨论(0)
  • 2020-11-22 16:59

    Assumes that AA only needs to be replaced if it is at the very start of the string:

    var newString;
    if(myString.StartsWith("AA"))
    {
      newString ="XQ" + myString.Substring(2);
    }
    

    If you need to replace the first occurrence of AA, whether the string starts with it or not, go with the solution from Marc.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题