C# string replace does not actually replace the value in the string(C#字符串替换实际上并不替换字符串中的值)
问题描述
我正在尝试用另一个字符串替换字符串的一部分.更准确地说我有 C:UsersDesktopProjectinDebug
I am trying to replace a part of string with another another string. To be more precise
I have C:UsersDesktopProjectinDebug
我正在尝试用 ResourcesPeople
我尝试了以下方法:
path.Replace(@"inDebug", @"ResourcePeopleVisitingFaculty.txt");
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?
推荐答案
问题是字符串是不可变的.replace、substring 等方法不会更改字符串本身.他们创建一个新字符串并替换它.所以上面的代码是正确的,应该是
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
path1 = path.Replace("\bin\Debug", "\Resource\People\VisitingFaculty.txt");
或者只是
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 对象是不可变的:它们一旦拥有就无法更改被创建.出现的所有 String 方法和 C# 运算符修改一个字符串实际上是在一个新的字符串对象中返回结果
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
这篇关于C#字符串替换实际上并不替换字符串中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#字符串替换实际上并不替换字符串中的值


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01