c# - 如何在逐字字符串中转义“?

标签 c# .net string escaping verbatim-string

<分区>

我对c#有点陌生,我被困在这一点上, 我有一个常规字符串,其中我使用 \ 来转义 ",此处转义意味着转义编译器对 " 的解释,并且" 打印在屏幕上,我得到了预期的输出-->

class Program
{
    static void Main(string[] args)
    {
        string s1 = "This is a \"regular\" string";
        System.Console.WriteLine(s1);
        System.Console.Read();
    }
}

o/p-->这是一个“常规”字符串

现在,我有一个逐字字符串,我正尝试以与上述相同的方式使用 \ 转义 "..-->

class Program
{
    static void Main(string[] args)
    {
        string s2 = @"This is \t a \"verbatim\" string";//this would escape \t
        System.Console.WriteLine(s2);
        System.Console.Read();
    }
}

为什么上面的方法不起作用?

最佳答案

使用双引号:

 string s2 = @"This is \t a ""verbatim"" string";

C# 11您还可以使用原始字符串文字,例如:

string longMessage = """
    This is a long message.
    It has several lines.
        Some are indented
                more than others.
    Some should start at the first column.
    Some have "quoted text" in them.
    """;

原始字符串文字是字符串文字的一种新格式。原始字符串文字可以包含任意文本,包括空格、换行符、嵌入引号和其他不需要转义序列的特殊字符。原始字符串文字至少以三个双引号 (""") 字符开头。它以相同数量的双引号字符结尾。

关于c# - 如何在逐字字符串中转义“?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17168961/

相关文章:

c# 什么 wpf 控件用于显示文本文件

c# - 如何从逻辑层访问 View ?

c# - 使用 Func<,> 构建 LambdaExpression,其中 returnType 为 IQueryable<T>

c# - 不为同步请求调用中间件

c# - 如何格式化传递给存储过程的数据以便与 IN 子句一起使用?

c# - 在哪里使用 EF6 订阅 ObjectMaterialized?

.net - 在 vb.net 中最佳使用 MID 和 INSTR

regex - 正则表达式对比字符串解析

python - python - 如何使用单行将列表/元组转换为python中的空格分隔字符串?

c# - 使用 .where 和 .select 从列表中的列表中选择单个元素