C# 特殊字符

字符串 - 特殊字符

由于字符串必须写在引号内,因此 C# 会误解下面的字符串,并产生错误:

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

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

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

转义字符 结果 描述
\' ' 单引号
\" " 双引号
\\ \ 反斜杠

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

实例

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

亲自试一试

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

实例

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

亲自试一试

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

实例

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

亲自试一试

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

代码 结果 试一试
\n 换行符 试一试
\t 制表符(Tab) 试一试
\b 退格符 试一试