C#替换串串 [英] C# replace string in string
问题描述
是否有可能替换字符串中的子串不分配一个返回值
我有一个字符串:
字符串测试=你好[REPLACE]的世界;
和我要替换的子 [REPLACE]
用别的东西:
检测= test.replace([REPLACE],测试);
这工作正常,但我怎么能做到这一点,而不返回值赋值给一个变量?我想是这样的:
test.replace([REPLACE],测试);
您不能,因为 字符串
是不可改变。它的目的是使任何改变为字符串实际上导致创建一个新的字符串
的对象。因此,如果你不指定返回值(这是更新的字符串,其实原来的字符串应用变化的复制),您将有效地丢弃你想进行更改。
如果你想使在发生的变化,你可以直接用的char []
(字符数组),但该理论工作是的危险的,应该尽量避免。
另一种选择(如下面飞碟双向先生指出的)是使用的StringBuilder
和替换()
方法。话虽这么说,像你已经证明了一个简单的替换都相当快,所以你可能不希望有打扰一个的StringBuilder
,除非你会做这样经常。
Is it possible to replace a substring in a string without assigning a return value?
I have a string:
string test = "Hello [REPLACE] world";
and I want to replace the substring [REPLACE]
with something else:
test = test.replace("[REPLACE]", "test");
This works fine but how can I do it without assigning the return value to a variable? I want something like this:
test.replace("[REPLACE]", "test");
You can't, because string
is immutable. It was designed so that any "changes" to a string would actually result in the creation of a new string
object. As such, if you don't assign the return value (which is the "updated" string, actually copy of the original string with applied changes), you have effectively discarded the changes you wanted to make.
If you wanted to make in-place changes, you could in theory work directly with a char[]
(array of characters), but that is dangerous, and should be avoided.
Another option (as pointed out by Mr. Skeet below) is to use StringBuilder
and its Replace()
method. That being said, simple replacements like the one you've shown are quite fast, so you may not want to bother with a StringBuilder
unless you'll be doing so quite often.
这篇关于C#替换串串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!