C#中的字符串替换 [英] string replacement in C#

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

问题描述


我的字符串包含"\\\\",我想将其替换为"\\".
例如:原始字符串为"domainName \\\\ myname",结果字符串应为"domainName \\ myname".

我已经尝试过string.Replace("\\\\","\\"),但这不起作用.

如何找到预期的结果字符串?.

谢谢.

Hi,
my string containing "\\\\" and I want to replace it with "\\".
eg: The Original string is "domainName\\\\myname" and resulted string should be "domainName\\myname".

I have tried string.Replace("\\\\", "\\") but this is not working.

How can I find expected resulted string?.

Thanks.

推荐答案

尝试以下代码:

Try this code:

string s = "\\\\";

string t = s.Replace("\\\\", "\\");



一切正常.也许,您没有考虑过争斗是一成不变的事实,从而解决了这个问题. string.replace将替换字符串并返回新字符串.它不会更新现有的字符串.

希望它对您有所帮助.让我知道我的理解是否正确.我将尝试完善答案.



This is working fine. Perhaps, you were not considering the fact that strigns are immutable and thus getting the problem. the string.replace will replace the string and return new string. it will not update the existing string.

Hope it helps and work for you. let me know if my understanding in not correct. i will try to refine my answer.


Dim str As String = "domainName\\\\myname"
     str = str.Replace("\\\\", "\\")



尝试使用转义序列("\")(反斜杠):
Try using escape sequence (''\'')(back slash):
stringOriginal.replace("\\\\\\\\","\\\\");  //if string contains 4 backslashes in actual this will replace with 2



此处的详细信息: MSDN:转义序列 [ domainName \\\\ myname "->认为这是错误的,您要纠正它.但是,这很好.您无需进行任何更改. "\"需要一个转义序列,CLR在计算时会自动应用它.应用该值时,它将仅是" domainName \\ myname ".
如果要避免混淆,请使用@字符定义字符串.
喜欢:



Details here: MSDN: Escape Sequences[^]


But, I believe actual issue would be that you are worried that your string is showing as ''domainName\\\\myname'' -> thinking this is wrong you want to correct it. But, this is perfectly fine. You don''t need to do any change. ''\'' needs a escape sequence and CLR automatically applies it at the time of computation. While applying the value it will be ''domainName\\myname'' only.
If you want to avoid confusion, define string with @ character.
Like:

string mypath = @"domainName\\myname";


这篇关于C#中的字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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