简体   繁体   English

替换C#中一个范围内的字符串

[英]replace a string within a range in C#

I have a string, myString, that is about 10000 in length. 我有一个字符串myString,长度约为10000。

If I do myString.Replace("A","B"); 如果我做myString.Replace("A","B"); It will replace all instances of A to B. 它将替换A到B的所有实例。

How can I do that not to the entire string but only to character 5000-5500? 我怎么能不这样做而不是整个字符串而只是字符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(). 它将需要比使用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. 使用SubString拆分字符串,并在操作完成时合并结果。

Or, iterate through the whole string as a char[] and (based on index) selectively perform the replace. 或者,迭代整个字符串作为char []和(基于索引)选择性地执行替换。 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: 拆分字符串以生成3个SubStrings,中间的一个是:

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

then glue them back together. 然后将它们粘在一起。

split the string from character 5000 to 5500 将字符串从字符5000拆分为5500

and then apply replace method 然后应用替换方法

then concat eachother 然后彼此结合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM