简体   繁体   English

用C#替换所有'\'字符到'/'

[英]Replacing all the '\' chars to '/' with C#

How can I replace all the '\\' chars in a string into '/' with C#? 如何用C#将字符串中的所有'\\'字符替换为'/'? For example, I need to make @"c:/abc/def" from @"c:\\abc\\def". 例如,我需要从@“c:\\ abc \\ def”创建@“c:/ abc / def”。

The Replace function seems suitable: 替换功能似乎合适:

string input = @"c:\abc\def";
string result = input.Replace(@"\", "/");

And be careful with a common gotcha: 并且要小心共同的问题:

Due to string immutability in .NET this function doesn't modify the string instance you are invoking it on => it returns the result. 由于.NET中的字符串不变性,此函数不会修改您在其上调用它的字符串实例=>它返回结果。

你需要逃避\\

mystring.Replace("\\", "/");
var replaced = originalStr.Replace( "\\", "/" );
var origString = origString.Replace(@"\", @"/");
@"C:\abc\def\".Replace(@"\", @"/");
string result = @"c:\asb\def".Replace(Path.DirectorySeparatorChar,Path.AltDirectorySeparatorChar);
string first = @"c:/abc/def";
string sec = first.Replace("/","\\");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM