Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET StringBuilder preappend a line

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.

like image 845
Art F Avatar asked Feb 18 '14 17:02

Art F


People also ask

How do you prepend in string builder?

Using the insert method with the position parameter set to 0 would be the same as prepending (i.e. inserting at the beginning). StringBuilder insert for java: java.sun.com/j2se/1.5.0/docs/api/java/lang/… The correct JavaDoc for the relevant API is: docs.oracle.com/javase/1.5.0/docs/api/java/lang/…

What is difference between append and AppendLine in StringBuilder C#?

Append: Appends information to the end of the current StringBuilder. AppendLine: Appends information as well as the default line terminator to the end of the current StringBuilder.

Can I append StringBuilder to StringBuilder?

StringBuilder has a public StringBuilder append(CharSequence s) method. StringBuilder implements the CharSequence interface, so you can pass a StringBuilder to that method.

Which method append a newline character to the end of string?

The AppendLine() method appends the content and add a new line on the end.


2 Answers

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); 
like image 69
Selman Genç Avatar answered Sep 22 '22 14:09

Selman Genç


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)
like image 36
Colin Bacon Avatar answered Sep 18 '22 14:09

Colin Bacon