.NET StringBuilder preappend a line

我与影子孤独终老i 提交于 2019-12-09 14:29:18

问题


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 StringBuilder. I know that you can use Insert() to append a string, but I can't seem to do that with a line, is there a next line character I can use? I am using VB.NET, so answers in that are preferable, but answers in C# are ok as well.


回答1:


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);



回答2:


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)


来源:https://stackoverflow.com/questions/21861366/net-stringbuilder-preappend-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!