我正在尝试用另一个字符串替换字符串的一部分。更准确地说
我有 C:\Users\Desktop\Project\bin\Debug
我正在尝试将 \bin\Debug
替换为 \Resources\People
我尝试了以下方法:
path.Replace(@"\bin\Debug", @"\Resource\People\VisitingFaculty.txt");
path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
以上两个似乎都不起作用,因为字符串保持不变并且没有任何内容被替换。难道我做错了什么?
问题是字符串是不可变的。 replace、substring 等方法不会更改字符串本身。他们创建一个新字符串并替换它。所以要使上面的代码正确,应该是
path1 = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
或者只是
path = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
如果不需要另一个变量。
这个答案也提醒我们字符串是不可变的。您对它们所做的任何更改实际上都会创建一个新字符串。因此,请记住涉及字符串的所有内容,包括内存管理。
如文档中所述 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