How to replace part of string by position?

2019-01-07 07:33发布

I have this string: ABCDEFGHIJ

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

It will look like this: ABCZXFGHIJ

But not to use with string.replace("DE","ZX") - I need to use with position

How can I do it?

15条回答
劳资没心,怎么记你
2楼-- · 2019-01-07 07:52

You could try something link this:

string str = "ABCDEFGHIJ";
str = str.Substring(0, 2) + "ZX" + str.Substring(5);
查看更多
等我变得足够好
3楼-- · 2019-01-07 07:55

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.

查看更多
We Are One
4楼-- · 2019-01-07 07:57
        string s = "ABCDEFG";
        string t = "st";
        s = s.Remove(4, t.Length);
        s = s.Insert(4, t);
查看更多
疯言疯语
5楼-- · 2019-01-07 07:57

It's better to use the String.substr().

Like this:

ReplString = GivenStr.substr(0, PostostarRelStr)
           + GivenStr(PostostarRelStr, ReplString.lenght());
查看更多
够拽才男人
6楼-- · 2019-01-07 07:59

Yet another

    public static string ReplaceAtPosition(this string self, int position, string newValue)        
    {
        return self.Remove(position, newValue.Length).Insert(position, newValue); 
    }
查看更多
Luminary・发光体
7楼-- · 2019-01-07 08:00

The easiest way to add and remove ranges in a string is to use the StringBuilder.

var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();

An alternative is to use String.Substring, but I think the StringBuilder code gets more readable.

查看更多
登录 后发表回答