我有一个字符串。我想搜索单斜杠,然后将“\”(单斜杠)替换为“\”(双斜杠)。
string Method1(string s)
{
string upadtedString = s;
if (s.Contains("\\"))
{
//do nothing
}
else if(s.Contains("\"))
{
string s1 = "\";
string s2 = "\\";
upadtedString.Replace(s1,s2);
s = upadtedString;
}
return s;
}
`
最佳答案
您需要转义反斜杠或使用逐字字符串文字,并且还要了解字符串是不可变的 - Replace
不会更改现有 字符串,它返回一个 < em>新字符串:
// Escaping with an extra backslash
updatedString = s.Replace("\\", "\\\\");
// Using a verbatim string literal
updatedString = s.Replace(@"\", @"\\");
有关转义和逐字字符串文字的更多信息,请参阅我的 strings article .
关于c# - 替换\与\\,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3457715/