c# - 使用转义序列连接两个字符串

标签 c# string escaping concatenation

我正在使用 C# 连接两个带有转义序列的字符串,我想跳过,所以我在每个字符串前使用 @ 符号。它看起来像这样:

string firstString = @"Use \n for line break. ";
string secondString = @"Use \b for backspace";
return firstString + secondString;

问题是:转义序列会在返回值中被跳过吗?;

最佳答案

其他答案当然是正确的。为了说清楚;

这包含在 section 2.4.4.5 of the C# specification 中:

2.4.4.5 String literals

C# supports two forms of string literals: regular string literals and verbatim string literals.

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

因此,当您将它与 verbtaim 字符串文字一起使用时;

string firstString = @"Use \n for line break. ";
string secondString = @"Use \b for backspace";
returns firstString + secondString; 

结果会是;

Use \n for line break. Use \b for backspace

当您使用常规字符串文字时;

string firstString = "Use \n for line break. ";
string secondString = "Use \b for backspace";
returns firstString + secondString; 

结果会是;

Use
 for line break. Use for backspace

因为 \n 是换行转义序列而 \b 是退格转义序列。对于所有列表,请查看;

关于c# - 使用转义序列连接两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19832281/

相关文章:

swift - 为什么我得到这个字符串值是 nil?

c# - 将字符串编码为 base-64 或从 base-64 编码

c# - 如何选择一条记录(按降序排列)?

c# - 当我将鼠标悬停在组合框项目上时引发事件

c# - 接口(interface)实现中成员的返回类型必须与接口(interface)定义完全匹配?

javascript - 使用 jQuery.css() 方法时是否需要转义任何字符?

python - 正则表达式无法逃脱问号?

c# - Odata如何授权用户角色的$expand功能?

ios - 缓慢的 Swift 字符串性能

java - 在字符串中写入html