user274364
user274364

Reputation: 1857

Newline character in StringBuilder

How do you append a new line(\n\r) character in StringBuilder?

Upvotes: 109

Views: 222429

Answers (8)

Paul Ishak
Paul Ishak

Reputation: 1093

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

Upvotes: 1

Lijo
Lijo

Reputation: 6778

Use StringBuilder's append line built-in functions:

StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");

Output

First line
Second line
Third line

Upvotes: 15

Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

Also, using the StringBuilder.AppendLine method.

Upvotes: 28

Ben Voigt
Ben Voigt

Reputation: 283614

With the AppendLine method.

َََ

Upvotes: 84

Adriaan Stander
Adriaan Stander

Reputation: 166356

I would make use of the 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();

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

Upvotes: 139

Janmejay Kumar
Janmejay Kumar

Reputation: 319

StringBuilder sb = new StringBuilder();

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

Upvotes: 4

user859400
user859400

Reputation: 83

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.

Upvotes: 1

Kerry Jiang
Kerry Jiang

Reputation: 1178

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

Upvotes: 7

Related Questions