Concatenating two strings with escape sequences

蹲街弑〆低调 提交于 2021-02-10 18:35:04

问题


I am using C# to concatenate two strings with escapes sequences, that i want to skip so I'm using @ symbol before each string. It looks like this:

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

The question is: Will that escapes sequences be skipped in the returned value?;


回答1:


Other answers are of course correct. For making it clear;

This is covered in 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.

So when you use it with verbtaim string literal like;

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

Result will be;

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

When you use regular string literal like;

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

Result will be;

Use
 for line break. Use for backspace

Because \n is new line escape sequence and \b is backspace escape sequence. For all list, take a look at;

  • Escape Sequences



回答2:


@"" is a verbatim string which treat's escape sequence as literals..

So \n \b would be escaped and would remain as it is..




回答3:


No, it will just print them out because they are treated as normal text due to the "@" symbol.

Why didn't you just run the code though?




回答4:


firstString + secondString Is a shortcut to String.Concat(firstString, secondString)

The Concat() method just concatenates the two strings as they are. It doesn't interpret their content. So the backslash characters will stay there.



来源:https://stackoverflow.com/questions/19832281/concatenating-two-strings-with-escape-sequences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!