How to replace part of string by position?

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

    I was looking for a solution with following requirements:

    1. use only a single, one-line expression
    2. use only system builtin methods (no custom implemented utility)

    Solution 1

    The solution that best suits me is this:

    // replace `oldString[i]` with `c`
    string newString = new StringBuilder(oldString).Replace(oldString[i], c, i, 1).ToString();
    

    This uses StringBuilder.Replace(oldChar, newChar, position, count)

    Solution 2

    The other solution that satisfies my requirements is to use Substring with concatenation:

    string newString = oldStr.Substring(0, i) + c + oldString.Substring(i+1, oldString.Length);
    

    This is OK too. I guess it's not as efficient as the first one performance wise (due to unnecessary string concatenation). But premature optimization is the root of all evil.

    So pick the one that you like the most :)

提交回复
热议问题