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

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

提交回复
热议问题