C#替换字符串中的字符串 [英] C# replace string in string

查看:41
本文介绍了C#替换字符串中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不分配返回值的情况下替换字符串中的子字符串?

Is it possible to replace a substring in a string without assigning a return value?

我有一个字符串:

string test = "Hello [REPLACE] world";

我想用别的东西替换子字符串 [REPLACE] :

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?

我想要这样的东西:

test.replace("[REPLACE]", "test");

推荐答案

正如 dlev 所提到的,你不能用 string 来做到这一点,因为字符串在 .NET - 一旦构造了一个字符串,您就无法做任何事情(不包括不安全的代码或反射)来更改内容.这使得字符串通常更容易使用,因为您无需担心防御性复制,它们自然是线程安全的等等.

As mentioned by dlev, you can't do this with string as strings are immutable in .NET - once a string has been constructed, there's nothing you can do (excluding unsafe code or reflection) to change the contents. This makes strings generally easier to work with, as you don't need to worry about defensive copying, they're naturally thread-safe etc.

然而,它的可变表亲是 StringBuilder - 它有一个 Replace 方法来执行对象内替换.例如:

Its mutable cousin, however, is StringBuilder - which has a Replace method to perform an in-object replacement. For example:

string x = "Hello [first] [second] world";

StringBuilder builder = new StringBuilder(x);
builder.Replace("[first]", "1st");
builder.Replace("[second]", "2nd");

string y = builder.ToString(); // Value of y is "Hello 1st 2nd world"

这篇关于C#替换字符串中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆