简体   繁体   English

如何在C#中替换字符

[英]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. 我想将字符串中的“ text3”更改为“ textabc”。 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... 字符串在C#中是不可变的,因此任何操作都会固有地创建一个新字符串。

From MSDN 从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. 由于这个事实, StringBuilders通常是对“字符串”执行操作的最有效方法。 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 . 请参见StringBuilder.Replace()方法-这不需要您将结果重新分配给另一个StringBuilder,因为它实际上会更改StringBuilder本身

Have a look at this article by the very famous Jon Skeet (you'll get to recongise him:)) all about using StringBuilder sensibly. 看看非常著名的Jon Skeet的 这篇文章 (您会认识他:)),所有有关明智地使用StringBuilder的文章。

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. 如前所述,字符串在.NET中是不可变的,也就是说,一旦创建,它们就无法更改。

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. 如果需要更大的灵活性,则可以使用StringBuilder ,在其中可以随意删除和替换字符串,最后使用其ToString方法将结果作为字符串实例。

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");

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

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