.NET StringBuilder preappend a line

前端 未结 2 1346
情歌与酒
情歌与酒 2021-02-18 14:41

I know that the System.Text.StringBuilder in .NET has an AppendLine() method, however, I need to pre-append a line to the beginning of a StringBu

相关标签:
2条回答
  • 2021-02-18 15:05

    is there a next line character I can use?

    You can use Environment.NewLine

    Gets the newline string defined for this environment.

    For example:

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("bla bla bla..");
    sb.Insert(0, Environment.NewLine);
    

    Or even better you can write a simple extension method for that:

    public static class MyExtensions
    {
        public static StringBuilder Prepend(this StringBuilder sb, string content)
        {
            return sb.Insert(0, content);
        }
    }
    

    Then you can use it like this:

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("bla bla bla..");
    sb.Prepend(Environment.NewLine);
    
    0 讨论(0)
  • 2021-02-18 15:05

    You can use AppendFormat to add a new line where ever you like.

    Dim sb As New StringBuilder()
    sb.AppendFormat("{0}Foo Bacon", Environment.NewLine)
    
    0 讨论(0)
提交回复
热议问题