How to replace part of string by position?

Gali picture Gali · Feb 16, 2011 · Viewed 254.5k times · Source

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?

Answer

Albin Sunnanbo picture Albin Sunnanbo · Feb 16, 2011

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.