How to append a newline to StringBuilder
Asked Answered
H

7

294

I have a StringBuilder object,

StringBuilder result = new StringBuilder();
result.append(someChar);

Now I want to append a newline character to the StringBuilder. How can I do it?

result.append("/n"); 

Does not work. So, I was thinking about writing a newline using Unicode. Will this help? If so, how can I add one?

Helsinki answered 26/1, 2013 at 7:13 Comment(2)
I thought it is "\n", or System.getProperty("line.separator").Hallucinosis
A newline is not necessarily a LINE FEED (LF) (Ascii/Unicode 10) character. As the correct answer points out, in Java you can get either one (LINE FEED or a platform-specific newline).Calve
S
609

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

Sorry answered 26/1, 2013 at 7:18 Comment(8)
+1 for the System.lineSeparator shortcut. The bigger question is why there isn't a StringBuilder#appendLine() method.Excitor
System.lineSeparator() documentation mentions "Returns the system-dependent line separator string.". This is not platform independant. Use this code if you need to write a string that will be used by the underlying operating system, otherwise use '\n'.Irisation
@Irisation - Why not just use System.lineSeparator() all the time? Why is '\n' a better option as default?Labio
No, System.lineSeparator() should be used when you deal with non-portable resources (that is, resources specific to the underlying operating system). It has a different value wether you are running Java on Windows (\r\n) or Unix (\n). If you use System.lineSeparator() all the time, you will therefore produce non portable files.Irisation
Unbelievable there's not already an appendLine overload on StringBuilder.Beachcomber
System.getProperty("line.separator") works in sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, digipaz.toString());Wariness
Any Android devs using Kotlin that may have stumbled here, this is what you're looking for https://mcmap.net/q/102118/-how-to-append-a-new-line-to-stringbuilder-in-kotlinAbode
In Kotlin I still just add "\n" to my string when I need it...Reichstag
H
30

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

Huggins answered 3/12, 2015 at 18:0 Comment(3)
... and since Java 8 there's StringJoiner, which "is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix." Using "\n" as delimiter would result in new lines (except for the last one). Internally, it uses a StringBuilder. The same approach could be realized using the Google Guava Joiner, I assume.Kerge
... and now this is deprecated. Please use org.apache.commons.text.TextStringBuilder.Regen
TextStringBuilder is not in commons-lang3, it is in commons-text commons.apache.org/proper/commons-textExtravasation
T
20

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

Tailpipe answered 26/1, 2013 at 7:17 Comment(0)
S
7

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
Sympetalous answered 6/7, 2017 at 5:26 Comment(0)
O
5

You can also use the line separator character in String.format (See java.util.Formatter), which is also platform agnostic.

i.e.:

result.append(String.format("%n", ""));

If you need to add more line spaces, just use:

result.append(String.format("%n%n", ""));

You can also use StringFormat to format your entire string, with a newline(s) at the end.

result.append(String.format("%10s%n%n", "This is my string."));
Otherworldly answered 18/5, 2017 at 21:23 Comment(0)
A
3

you can use line.seperator for appending new line in

Aphorize answered 29/9, 2016 at 20:45 Comment(0)
B
3

In addition to K.S's response of creating a StringBuilderPlus class and utilising ther adapter pattern to extend a final class, if you make use of generics and return the StringBuilderPlus object in the new append and appendLine methods, you can make use of the StringBuilders many append methods for all different types, while regaining the ability to string string multiple append commands together, as shown below

public class StringBuilderPlus {

    private final StringBuilder stringBuilder;

    public StringBuilderPlus() {
        this.stringBuilder = new StringBuilder();
    }

    public <T> StringBuilderPlus append(T t) {
        stringBuilder.append(t);
        return this;
    }

    public <T> StringBuilderPlus appendLine(T t) {
        stringBuilder.append(t).append(System.lineSeparator());
        return this;
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }

    public StringBuilder getStringBuilder() {
        return stringBuilder;
    }
}

you can then use this exactly like the original StringBuilder class:

StringBuilderPlus stringBuilder = new StringBuilderPlus();
stringBuilder.appendLine("test")
    .appendLine('c')
    .appendLine(1)
    .appendLine(1.2)
    .appendLine(1L);

stringBuilder.toString();
Bailor answered 8/1, 2020 at 13:30 Comment(1)
there is quite a few conversion problems here.Offoffbroadway

© 2022 - 2024 — McMap. All rights reserved.