为什么这个替换反斜杠不起作用?(Why isn't this replace of backslash working?)

编程入门 行业动态 更新时间:2024-10-22 13:34:42
为什么这个替换反斜杠不起作用?(Why isn't this replace of backslash working?)

所以我需要从字符串中删除转义的反斜杠(在我的例子中,路径就像“C:\ Program Files(x86)\ Microsoft Office \ Office14 \ WINWORD.EXE \”)。

要替换我已经尝试过以下内容:

String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; string newString = openWith.Replace(@"\\", @"\"); openWith = openWith.Replace(@"\\", @"\"); openWith = Regex.Replace(openWith,"\\\\","\\");

但这些都不起作用!! 有人能够向我解释为什么会这样吗?

先感谢您!

So I need to remove escaped backslashes from a string (in my case, a path simply like "C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE\").

To replace I've tried the following:

String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; string newString = openWith.Replace(@"\\", @"\"); openWith = openWith.Replace(@"\\", @"\"); openWith = Regex.Replace(openWith,"\\\\","\\");

But none of these work!! Would anyone be able to explain to me why this may be?

Thank you in advance!

最满意答案

您的字符串不包含加倍的反斜杠。

"C:\\"的第一个反斜杠是一个转义字符,由C#编译器解释。 但是在运行时,字符串只包含单个反斜杠。 您可以通过显示字符串的值来证明这一点:

String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; Console.WriteLine(openWith);

结果:

C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE

请注意,输出中只有一个反斜杠。

看它在线工作: ideone

Your string doesn't contain doubled backslashes.

The first backslash in "C:\\" is an escape character which is interpreted by the C# compiler. At runtime however the string only contains single backslashes. You can prove this to yourself by displaying the value of the string:

String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; Console.WriteLine(openWith);

Result:

C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE

Note that there are only single backslashes in the output.

See it working online: ideone

更多推荐

本文发布于:2023-08-07 19:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465558.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   不起作用   replace   backslash   working

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!