Newline character in stringbuilder

走远了吗. 提交于 2019-11-30 07:47:29

I would make use of Environment.NewLine Property

Something like

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();

Or

StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();

EDIT:

If you wish to have a new line after each append, you can have a look at @Ben Voigt answer.

also, using StringBuilder.AppendLine method.

Kerry Jiang

It will append \n in Linux instead \r\n.

Use String builder append line inbuilt functions

StringBuilder sb = new StringBuilder();
sb.AppendLine("first line ");
sb.AppendLine("Second  line ");
sb.AppendLine("third  line ");

output

firstline Second line third line

For multiple lines the best way I find is to do this:

        IEnumerable<string> lines = new List<string>
        {
            string.Format("{{ line with formatting... {0} }}", id),
            "line 2",
            "line 3"
        };
        StringBuilder sb = new StringBuilder();
        foreach(var line in lines)
            sb.AppendLine(line);

In this way you don't have to clutter the screen with the Environment.NewLine or AppendLine() repeated multiple times. It will also be less error prone than having to remember to type them.

StringBuilder sb = new StringBuilder();

You can use sb.AppendLine() or sb.Append(Environment.NewLine);

Why not just create an extension for the stringbuilder class?

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!