c# - stringbuilder 将初始字符添加到每个新行

标签 c#

目前我有一个带有一些行的 StringBuilder

        StringBuilder foo = new StringBuilder()
            .AppendLine("- one")
            .AppendLine("- two")
            .AppendLine("- three");

我想为每一行设置 "- " 字符。伪代码:

        StringBuilder foo = new StringBuilder()
            .SetNewLineInitialCharacter("- ")
            .AppendLine("one")
            .AppendLine("two")
            .AppendLine("three");

我不认为 InsertReplace 是我正在寻找的方法。我知道循环可以解决问题,但没有必要,我只是想问一下是否有办法一次性设置 "- "

最佳答案

您可以使用包装的 StringBuilder 来做到这一点:

public class StringBuilderWrapper
{
    private readonly string _prefix;
    private readonly StringBuilder _builder;

    public StringBuilderWrapper(StringBuilder builder, string prefix)
    {
        _prefix = prefix;
        _builder = builder;
    }

    public StringBuilderWrapper AppendLine(string line)
    {
        _builder.Append(_prefix);
        _builder.AppendLine(line);

        return this;
    }

    public override string ToString()
    {
        return _builder.ToString(); 
    }
}

为了方便起见,您可以从扩展方法中返回:

public static class StringBuilderExtensions
{
    public static StringBuilderWrapper SetNewLineInitialCharacter(this StringBuilder builder, string prefix)
    {
        return new StringBuilderWrapper(builder, prefix);
    }
}

然后这样调用它:

var output = new StringBuilder()
    .SetNewLineInitialCharacter("- ")
    .AppendLine("one")
    .AppendLine("two")
    .AppendLine("three");

var outputString = output.ToString();

哪些输出:

- one
- two
- three

如果没有扩展方法,你可以这样调用它:

var output = new StringBuilderWrapper(new StringBuilder(), "- ")
    .AppendLine("one")
    .AppendLine("two")
    .AppendLine("three");

关于c# - stringbuilder 将初始字符添加到每个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53429820/

相关文章:

c# - 无法在 asp.net core api 3.1 中将 [FromForm] 枚举与 [EnumMember] 映射

c# - 我可以为 .NET Windows 窗体窗口中的工具提示设置无限的 AutoPopDelay 吗?

c# - Saxon 9 Compiled Transform 的线程安全

c# - Roslyn - 如何在 DiagnosticAnalyzer 类中获取变量的所有引用?

c# - 如何正确部署托管/非托管 C++ 库

C# 如何在类中使用 get、set 和使用枚举

c# - 在没有实例的情况下获取字段类型默认值

c# - Controller 的自定义脚手架

c# - 过滤掉重复和包含列表的最佳/性能最佳方法

c# - 将多个参数从 IronPython 传递到 .NET 方法