C# 字符串替换实际上并不替换字符串中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13277667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:03:20  来源:igfitidea点击:

C# string replace does not actually replace the value in the string

c#.netstring

提问by John Demetriou

I am trying to replace a part of string with another another string. To be more precise I have C:\Users\Desktop\Project\bin\Debug

我试图用另一个字符串替换字符串的一部分。更准确地说,我有 C:\Users\Desktop\Project\bin\Debug

and I am trying to replace \bin\Debugwith \Resources\People

我试图取代\bin\Debug\Resources\People

I have tried the following:

我尝试了以下方法:

  1. path.Replace(@"\bin\Debug", @"\Resource\People\VisitingFaculty.txt");

  2. path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");

  1. path.Replace(@"\bin\Debug", @"\Resource\People\VisitingFaculty.txt");

  2. path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");

None of the above two seems to work, as the string remains the same and nothing is replaced. Am I doing something wrong?

以上两个似乎都不起作用,因为字符串保持不变并且没有替换任何内容。难道我做错了什么?

采纳答案by John Demetriou

The problem is that strings are immutable. The methods replace, substring etc do not change the string itself. They create a new string and replace it. So for the above code to be correct it should be

问题是字符串是不可变的。方法 replace、substring 等不会改变字符串本身。他们创建一个新字符串并替换它。所以为了上面的代码是正确的,它应该是

path1 = path.Replace("\bin\Debug", "\Resource\People\VisitingFaculty.txt");

Or just

要不就

path = path.Replace("\bin\Debug", "\Resource\People\VisitingFaculty.txt");

if another variable is not needed

如果不需要另一个变量

This answer is also a reminder that strings are immutable. Any change you make to them will in fact create a new string. So keep that in mind with everything that involves strings, including memory management. As stated in the documentation here

这个答案也提醒我们字符串是不可变的。您对它们所做的任何更改实际上都会创建一个新字符串。因此,请记住涉及字符串的所有内容,包括内存管理。如文档中说明这里

String objects are immutable: they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object

String 对象是不可变的:它们在创建后无法更改。所有看似修改字符串的 String 方法和 C# 运算符实际上都返回一个新字符串对象中的结果

回答by PaulG

The path.Replacemethod actually returns a string. You should do the following:

path.Replace方法实际上返回一个string. 您应该执行以下操作:

path = path.Replace("firstString", "secondString");

回答by SKJ

String.Replace(string,string) returns string. 

So, save the new path in some string variable.

因此,将新路径保存在某个字符串变量中。

path = path.Replace("\bin\Debug", "\Resource\People\VisitingFaculty.txt");