[英]How to quote \" (slash double-quote) in a string literal?
This is probably a really simple question but I can't seem to get my head around it. 这可能是一个非常简单的问题,但我似乎无法理解它。 I need to have a string that contains
\\"
without it seeing it as an escape character. I tried using @
but it won't work. The only other way I thought of doing this would be to use "
but don't want to unless I can help it. 我需要一个包含
\\"
的字符串, \\"
它没有把它视为一个转义字符。我尝试使用@
但它不起作用。我想这样做的另一种方法是使用"
但不想要除非我能帮助它。
Desired string - string s = "\\"\\""; // Obviously this doesn't work!
所需的字符串 -
string s = "\\"\\""; // Obviously this doesn't work!
string s = "\\"\\""; // Obviously this doesn't work!
Desired console output - \\"\\"
所需的控制台输出 -
\\"\\"
Hope this makes sense. 希望这是有道理的。
Thanks! 谢谢!
Try 尝试
string s = "\\\"\\\"";
You have to escape your backslashes too. 你也必须逃避你的反斜杠。
Mike 麦克风
In verbatim string literals ( @"..."
) a "
in the string value is encoded as ""
, which happens to also be the only escape sequence in verbatim strings. 在逐字字符串文字(
@"..."
)中, "
字符串值中的”被编码为""
,这恰好也是逐字字符串中唯一的转义序列。
@"\""Happy coding!\""" // => \"Happy coding!\"
"\\\"Happy coding!\\\"" // => \"Happy coding!\"
Note that in the 2nd case (not a verbatim string literal), a \\
is required before the \\
and the "
to escape them and prevent their normal meanings. 请注意,在第二种情况下(不是逐字字符串文字),在
\\
之前需要\\
和 "
以逃避它们并防止它们的正常含义。
See the C# string reference for more details and examples. 有关更多详细信息和示例,请参阅C#字符串参考 。
您可以使用文字,但需要加倍引号。
string s = @"\""\""";
我认为你也必须逃避反斜杠...所以像"\\\\\\"\\\\\\""
这样的东西应该有效,我相信。
使用此字符串:
string s = "\\\"\\\"";
Console.WriteLine( "\\\"\\\"" );
只需在需要打印的每个字符前放一个\\
。
String s = @"\""\""";
DblQuote characters will escape a second dblquote character DblQuote字符将转义第二个dblquote字符
Though for better readability I would go with: 虽然为了更好的可读性,我会选择:
const String DOUBLEQUOTE = """";
const String BACKSLASH = @"\";
String s = BACKSLASH + DOUBLEQUITE + BACKSLASH + DOUBLEQUOTE;
In a verbatim string (a string starting with @""
) to escape double quotes you use double quotes, eg @"Please press ""Ok""."
在逐字字符串(以
@""
开头的字符串)中,要使用双引号, @"Please press ""Ok""."
使用双引号,例如@"Please press ""Ok""."
. 。 If you want to do it with verbatim strings then you would do something like
@"\\"""
(that's 3 double quotes on the end there). 如果你想用逐字字符串来做,那么你会做类似
@"\\"""
(那里有3个双引号)。
You can do like this, 你可以这样做,
string s = "something'\\\'";
Use a single '' rather then "" in string to do the same. 在字符串中使用单个“而不是”“来执行相同操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.