How to replace part of string by position?

后端 未结 18 919
逝去的感伤
逝去的感伤 2020-11-28 04:37

I have this string: ABCDEFGHIJ

I need to replace from position 4 to position 5 with the string ZX

It will look like this: ABC

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 05:12

    Like other have mentioned the Substring() function is there for a reason:

    static void Main(string[] args)
    {
        string input = "ABCDEFGHIJ";
    
        string output = input.Overwrite(3, "ZX"); // 4th position has index 3
        // ABCZXFGHIJ
    }
    
    public static string Overwrite(this string text, int position, string new_text)
    {
        return text.Substring(0, position) + new_text + text.Substring(position + new_text.Length);
    }
    

    Also I timed this against the StringBuilder solution and got 900 tics vs. 875. So it is slightly slower.

提交回复
热议问题