简体   繁体   中英

How can I substitute characters in C#

I have strings like this:

var abc = "text1 text2 text3";

I want to change "text3" to "textabc" in the string. Is there a way that I can do this without creating a new string?

Strings are immutable in C# so any operation inherently creates a new string...

From MSDN

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

StringBuilders are often the most efficient way to perform manipulation on a "string" due to this fact. Especially if you are concatenating one char at a time for example.

See the StringBuilder.Replace() method - This does not require you reassign the result to another StringBuilder as it actually changes the StringBuilder itself .

Have a look at this article by the very famous Jon Skeet (you'll get to recongise him:)) all about using StringBuilder sensibly.

string newString = abc.Replace("text3", "textabc");

字符串在CLR中是不可变的:您永远都无法更改它们。

The main question is what do you mean by writing "without creating a new string".

As stated, strings are immutable in .NET, that is, once they're created, they can't change.

However, you can replace them with a new string instance:

var abc = "text1 text2 text3";  
abc = abc.Replace("text3", "textabc");

If you want more flexibility, you may want to use StringBuilder , in which you can remove and replace strings as much as you want, and finally use its ToString method to have the result as a string instance.

No, because strings are immutable, but you can reassign the new string to the same variable

var abc = "text1 text2 text3"
abc = abc.Replace("text3", "textabc");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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