C# replace string in string

后端 未结 7 1219
情歌与酒
情歌与酒 2020-12-09 10:57

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

I have a string:

string test = "Hello [REPLACE] world";
<         


        
7条回答
  •  天命终不由人
    2020-12-09 11:14

    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.

    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"
    

提交回复
热议问题