How to replace part of string by position?

后端 未结 18 910
逝去的感伤
逝去的感伤 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:29

    With the help of this post, I create following function with additional length checks

    public string ReplaceStringByIndex(string original, string replaceWith, int replaceIndex)
    {
        if (original.Length >= (replaceIndex + replaceWith.Length))
        {
            StringBuilder rev = new StringBuilder(original);
            rev.Remove(replaceIndex, replaceWith.Length);
            rev.Insert(replaceIndex, replaceWith);
            return rev.ToString();
        }
        else
        {
            throw new Exception("Wrong lengths for the operation");
        }
    }
    

提交回复
热议问题