Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a newline to StringBuilder

People also ask

How do you append to next line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

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

AppendLine() Appends the default line terminator to the end of the current StringBuilder object.

Can I append string to StringBuilder?

append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.


It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()


Another option is to use Apache Commons StrBuilder, which has the functionality that's lacking in StringBuilder.

StrBuilder.appendLn()

As of version 3.6 StrBuilder has been deprecated in favour of TextStringBuilder which has the same functionality


Escape should be done with \, not /.

So r.append('\n'); or r.append("\n"); will work (StringBuilder has overloaded methods for char and String type).


I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Usage:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Console:

aaaaa
bbbbb

For Kotlin,

StringBuilder().appendLine("your text");

Though this is a java question, this is also the first google result for Kotlin, might come in handy.