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

标签 c# .net string multiline verbatim-string

我喜欢在 C# 中使用 @"strings",尤其是当我有很多多行文本时。唯一令人烦恼的是,在执行此操作时,我的代码格式变得糟糕,因为第二行和更多行被完全推到左侧,而不是使用我格式精美的代码的缩进。我知道这是设计使然,但是是否有一些选项/破解方法允许缩进这些行,而不向输出添加实际的制表符/空格?

添加示例:

        var MyString = @" this is 
a multi-line string
in c#.";

我的变量声明缩进到“正确”的深度,但字符串中的第二行和更多行被推到左边距 - 所以代码有点难看。您可以将制表符添加到第 2 行和第 3 行的开头,但字符串本身将包含这些制表符……有意义吗?

最佳答案

字符串扩展怎么样?更新:我重读了你的问题,希望有更好的答案。这也是让我烦恼的事情,不得不按照下面的方式解决它令人沮丧,但从好的方面来说它确实有效。

using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    public static class StringExtensions
    {
        public static string StripLeadingWhitespace(this string s)
        {
            Regex r = new Regex(@"^\s+", RegexOptions.Multiline);
            return r.Replace(s, string.Empty);
        }
    }
}

还有一个示例控制台程序:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = @"This is a test
                of the emergency
                broadcasting system.";

            Console.WriteLine(x);

            Console.WriteLine();
            Console.WriteLine("---");
            Console.WriteLine();

            Console.WriteLine(x.StripLeadingWhitespace());

            Console.ReadKey();
        }
    }
}

输出:

This is a test
                of the emergency
                broadcasting system.

---

This is a test
of the emergency
broadcasting system.

如果您决定走这条路,还有一种更简洁的使用方式:

string x = @"This is a test
    of the emergency
    broadcasting system.".StripLeadingWhitespace();
// consider renaming extension to say TrimIndent() or similar if used this way

关于c# - c#中逐字字符串的多行格式(前缀为@),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7178136/

相关文章:

c# - 将 IP 地址转换并显示为二进制形式?

c# - 为什么 OpenFileDialog 需要 Microsoft.Win32?

c# - 按键时将焦点集中到文本框

c# - Linq、模拟联接和 Include 方法

.net - 面向 VB6 程序员的 VB.NET 中的 VB 运行时函数

string - 这是 "string pattern matching"算法吗?或者是其他东西?

c# - 如何从 C# 中的 dataGridView 更新 mysql 数据库

c# - 通过 google S3 api 访问存储桶

java - 如何在java中通过字符串名称使用实例化对象?

java - 在 JNI 中获取并打印字符串数组