C# replace string in string

后端 未结 7 1187
情歌与酒
情歌与酒 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:24

    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.

    0 讨论(0)
提交回复
热议问题