Replace string within range in C #

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.

How can I do this not for the whole line, but only for the character 5000-5500?

+6
c #
source share
5 answers
 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 ().

+18
source share
 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; 
+1
source share

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.

0
source share

Divide the line to make 3 substrings, the middle of which is:

myString.Substring (5000, 500) .Replace ("A", "B");

then glue them back together.

0
source share

divide the line from character 5000 to 5500

and then apply the substitution method

then concat eachother

0
source share

All Articles