How to append a newline to StringBuilder

JavaStringbuilder

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

you can use line.seperator for appending new line in

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIllepView Question on Stackoverflow
Solution 1 - JavaJayamohanView Answer on Stackoverflow
Solution 2 - JavaHalf_DuplexView Answer on Stackoverflow
Solution 3 - JavanhahtdhView Answer on Stackoverflow
Solution 4 - JavaK.SView Answer on Stackoverflow
Solution 5 - JavaRashida HasanView Answer on Stackoverflow
Solution 6 - JavaRoxanneView Answer on Stackoverflow
Solution 7 - Javafarhan patelView Answer on Stackoverflow
Solution 8 - JavaBoc DevView Answer on Stackoverflow