I have a string myString with a length of about 10,000.
If I do myString.Replace("A","B"); It will replace all instances of A with B.
myString.Replace("A","B");
How can I do this not for the whole line, but only for the character 5000-5500?
StringBuilder myStringBuilder = new StringBuilder(myString); myStringBuilder.Replace("A", "B", 5000, 500); myString = myStringBuilder.ToString();
This will require less memory allocation than methods using String.Substring ().
var sub1 = myString.SubString(0,4999); var sub2 = myString.SubString(5000,500); var sub3 = myString.SubString(5501,myString.Length-5501); var result = sub1 + sub2.Replace("A","B") + sub3;
Split the string using SubString and merge the results when the operation is complete.
Or, iterating over the entire string as char [] and (by index) selectively perform the replacement. This will not create so many new line instances, but will be more fragile.
Divide the line to make 3 substrings, the middle of which is:
myString.Substring (5000, 500) .Replace ("A", "B");
then glue them back together.
divide the line from character 5000 to 5500
and then apply the substitution method
then concat eachother