gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:40:01 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com