How to replace part of string by position?
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?
string s = "ABCDEFGH";
s= s.Remove(3, 2).Insert(3, "ZX");
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.