Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a string within a range in C#

Tags:

c#

.net

I have a string, myString, that is about 10000 in length.

If I do myString.Replace("A","B"); It will replace all instances of A to B.

How can I do that not to the entire string but only to character 5000-5500?

like image 241
Rana Avatar asked Oct 06 '10 08:10

Rana


2 Answers

StringBuilder myStringBuilder = new StringBuilder(myString);
myStringBuilder.Replace("A", "B", 5000, 500);
myString = myStringBuilder.ToString();

It will require less memory allocations then methods using String.Substring().

like image 100
cement Avatar answered Sep 28 '22 13:09

cement


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;
like image 44
bitbonk Avatar answered Sep 28 '22 13:09

bitbonk