C#字符串替换实际上不会替换字符串中的值 [英] C# string replace does not actually replace the value in the string

查看:127
本文介绍了C#字符串替换实际上不会替换字符串中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用另一个字符串替换另一个字符串。更确切地说
我有 C:\Users\Desktop\Project\bin\Debug

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

,而我正尝试将 \bin\Debug 替换为 \资源\人

and I am trying to replace \bin\Debug with \Resources\People

我尝试了以下操作:


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

path.Replace( \\bin\\Debug, \\资源\\人\\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");

如果不需要其他变量

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

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方法和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#字符串替换实际上不会替换字符串中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆