c# - 逐字字符串文字中的新行

标签 c# verbatim-string

我有一个字符串如下:

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

单行输出如下:

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

我需要如下输出:

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

如何在此逐字字符串文字中的“char pad”之前插入换行符

最佳答案

在逐字字符串文字中,除了两个双引号外,所有转义字符都逐字解释,因此如果您想要两行字符串,则必须手动将其写成两行:

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

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

来自 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]

关于c# - 逐字字符串文字中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097012/

相关文章:

c# - Windows Phone中的RestSharp同步请求

c# - LINQ groupby 到 List<List<object>>

c# - 通过 ssl 调用 web 服务并使用客户端传递

c# - 为什么从我的逐字字符串中删除换行符只返回最后一行?

c# - C#中字符串前面的@是什么?

c# - c#中逐字字符串的多行格式(前缀为@)

vb.net - 防止 VB.NET 的多行/逐字字符串破坏您的整个代码文件?

c# - 在属性构造函数中使用 Lambda 获取方法的参数

c# - MembershipProvider 的密码验证器?