Rana
Rana

Reputation: 4611

replace a string within a range in C#

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?

Upvotes: 7

Views: 5276

Answers (5)

bitbonk
bitbonk

Reputation: 49639

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;

Upvotes: 2

hemant kambli
hemant kambli

Reputation: 253

split the string from character 5000 to 5500

and then apply replace method

then concat eachother

Upvotes: 0

cement
cement

Reputation: 2905

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().

Upvotes: 21

Brissles
Brissles

Reputation: 3891

Split the string to make 3 SubStrings, the middle one being:

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

then glue them back together.

Upvotes: 0

Tim M.
Tim M.

Reputation: 54377

Split the string using SubString, and combine the results when the operation is complete.

Or, iterate through the whole string as a char[] and (based on index) selectively perform the replace. This will not create as many new string instances, but it is more brittle.

Upvotes: 0

Related Questions