Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put spaces in a stringbuilder

Hello I have following method to display a promotion line when I comment a shoutbox:

public String getShoutboxUnderline(){
        StringBuilder builder = new StringBuilder();
        builder.append("watch");
        builder.append("on");
        builder.append("youtube");
        builder.append(":");
        builder.append("Mickey");
        builder.append("en");
        builder.append("de");
        builder.append("stomende");
        builder.append("drol");

        return builder.toString();
    }

But when I get it, I get watchonyoutube:mickeyendestomendedrol, which is without spaces. How do I get spaces in my Stringbuilder?

like image 331
KeinHappyAuer Avatar asked Jan 26 '16 12:01

KeinHappyAuer


People also ask

How do you add a space in a StringBuffer?

StringJoiner 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. StringJoiner joiner = new StringJoiner(" "); // Use 'space' as the delimiter joiner. add("watch") // watch . add("on") // watch on .

How do you add a space to a StringBuffer in Java?

When we append the content to a StringBuffer object, the content gets appended to the end of sequence without any spaces and line breaks. For example: StringBuffer sb= new StringBuffer("Hello,"); sb. append("How"); sb.

What is the space complexity of StringBuilder?

Each time you append the StringBuilder it checks if the builder array is filled, if required copies the contents of original array to new array of increased size. So the space requirement increases linearly with the length of String. Hence the space complexity is O(n) .

How do I remove spaces in StringBuilder?

StringBuilder str = new StringBuilder("Patience is key!"); To remove whitespace, you can use the replace method. str.


1 Answers

As of JDK 1.8, you can use a StringJoiner, which is more convenient in your case:

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

StringJoiner joiner = new StringJoiner(" "); // Use 'space' as the delimiter
joiner.add("watch") // watch 
      .add("on") // watch on 
      .add("youtube") // watch on youtube
      .add(":") // etc...
      .add("Mickey")
      .add("en")
      .add("de")
      .add("stomende")
      .add("drol");

return joiner.toString();

This way, you will not need to add those spaces "manually".

like image 165
Mohammed Aouf Zouag Avatar answered Oct 18 '22 09:10

Mohammed Aouf Zouag