替换\\在C#\ [英] Replace \\ with \ in C#
问题描述
我有一个很长的字符串(路径)用双反斜线,我想单反斜线来替代它:
字符串=a\\b\\c\\d;
字符串B = a.Replace(@\\,@\);
此代码做什么...
b
仍然a\\b\\c\\d
我也试过,而不是使用 @
反斜杠的不同组合,但没有运气。
< DIV CLASS =h2_lin>解决方案
在C#中,你不能有像a\b\c\d$ C $字符串C>,因为
\
有特殊的意义:它创建一个的转义序列与下面的字母(或数字组合)一起的。
\ b
表示实际上是一个退格键和 \c
和 \d
无效逃生序列(编译器会抱怨一个无法识别的转义序列)。
那么,你如何创建一个简单的 \ 字符串code>?你必须使用一个反斜杠ESPACE反斜杠:
\\
(它的协商序列表示单个反斜线)
这意味着字符串a\\b\\c\\d
实际上代表 A \b\c\d
(这并不代表 a\\b\\c\\d
,所以没有双反斜线)。你会看到自己,如果你尝试打印此字符串。
C#也有一个叫做的逐字字符串(字符串与启动@
),它允许你写 @a\b\c\d
而不是a\\b\\c\\\的\\d
。
I have a long string (a path) with double backslashes, and I want to replace it with single backslashes:
string a = "a\\b\\c\\d";
string b = a.Replace(@"\\", @"\");
This code does nothing...
b
remains "a\\b\\c\\d"
I also tried different combinations of backslashes instead of using @
, but no luck.
In C#, you can't have a string like "a\b\c\d"
, because the \
has a special meaning: it creates a escape sequence together with a following letter (or combination of digits).
\b
represents actually a backspace, and \c
and \d
are invalid escape sequences (the compiler will complain about an "Unrecognized escape sequence").
So how do you create a string with a simple \
? You have to use a backslash to espace the backslash:\\
(it's the espace sequence that represents a single backslash).
That means that the string "a\\b\\c\\d"
actually represents a\b\c\d
(it doesn't represent a\\b\\c\\d
, so no double backslashes). You'll see it yourself if you try to print this string.
C# also has a feature called verbatim string literals (strings that start with @
), which allows you to write @"a\b\c\d"
instead of "a\\b\\c\\d"
.
这篇关于替换\\在C#\的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!