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

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

    Taking the "first only" into account, perhaps:

    int index = input.IndexOf("AA");
    if (index >= 0) output = input.Substring(0, index) + "XQ" +
         input.Substring(index + 2);
    

    ?

    Or more generally:

    public static string ReplaceFirstInstance(this string source,
        string find, string replace)
    {
        int index = source.IndexOf(find);
        return index < 0 ? source : source.Substring(0, index) + replace +
             source.Substring(index + find.Length);
    }
    

    Then:

    string output = input.ReplaceFirstInstance("AA", "XQ");
    

提交回复
热议问题