Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line in a verbatim string literal

I have a string as follows:

string example = @"string str = ""forty-two"";
char pad = '*';

the output is in a single line as follows:

string str = "forty-two"; char pad = '*';

I need the output as follows:

string str = "forty-two"; 
char pad = '*';

How can I insert newline before 'char pad' in this verbatim string literal

like image 535
A. F. M. Golam Kibria Avatar asked Jun 28 '15 06:06

A. F. M. Golam Kibria


People also ask

How do you add a new line to a string literal?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is a verbatim string literal?

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".

What is a verbatim string literal and why do we use it?

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.


1 Answers

In a verbatim string literal, apart from two double quotes all the escape characters are interpreted verbatim, so if you want a two-line string you have to manually write it in two lines:

string example = @"string str = ""forty-two"";
char pad = '*';";

Console.WriteLine(example); // string str = "forty-two";
                            // char pad = '*';

From msdn:

A string literal such as @"c:\Foo" is called a verbatim string literal. It basically means, "don't apply any interpretations to characters until the next quote character is reached". So, a verbatim string literal can contain backslashes (without them being doubled-up) and even line separators. To get a double-quote (") within a verbatim literal, you need to just double it, e.g. @"My name is ""Jon""" represents the string My name is "Jon". Verbatim string literals which contain line separators will also contain the white-space at the start of the line, so I tend not to use them in cases where the white-space matters. They're very handy for including XML or SQL in your source code though, and another typical use (which doesn't need line separators) is for specifying a file system path.

It's worth noting that it doesn't affect the string itself in any way: a string specified as a verbatim string literal is exactly the same as a string specified as a normal string literal with appropriate escaping. The debugger will sometimes choose to display a string as a verbatim string literal - this is solely for ease of viewing the string's contents without worrying about escaping.

[Author: Jon Skeet]

like image 177
w.b Avatar answered Oct 13 '22 00:10

w.b