开发者

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?


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


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


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

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

then glue them back together.


split the string from character 5000 to 5500

and then apply replace method

then concat eachother

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜