C# 特殊字符


字符串 - 特殊字符

因为字符串必须写在引号内,所以 C# 将误解该字符串,并生成错误:

string txt = "We are the so-called "Vikings" from the north.";

避免这个问题的解决方案是使用反斜杠转义字符

反斜杠 (\) 转义字符将特殊字符转换为字符串字符:

Escape character Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

序列\"在字符串中插入双引号:

示例

string txt = "We are the so-called \"Vikings\" from the north.";

亲自试一试 »

序列\'在字符串中插入单引号:

示例

string txt = "It\'s alright.";

亲自试一试 »

序列\\在字符串中插入单个反斜杠:

示例

string txt = "The character \\ is called backslash.";

亲自试一试 »

C# 中其他有用的转义字符有:

Code Result 尝试一下
\n New Line 尝试一下 »
\t Tab 尝试一下 »
\b Backspace 尝试一下 »

C# 练习

通过练习测试一下

练习:

填写缺失的部分以创建greeting类型变量string并为其赋值Hello

  = ;

开始练习