How to put spaces in a string server

Hello, I have the following ad line display method when I comment on cricket:

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 to get spaces in my Stringbuilder?

+7
java string stringbuilder
source share
4 answers

With JDK 1.8 you can use StringJoiner , which is more convenient in your case:

StringJoiner used to construct a sequence of characters separated by a separator and optionally , starting with the attached prefix and ending with the 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(); 

Thus, you will not need to add these spaces β€œmanually”.

+21
source share

Just enter builder.append(" ") at the location of your preference.

eg.

 builder .append("watch") .append(" ") .append("on") 

... etc..

Note:

  • Using free manual syntax for convenience
  • You can also just add a space after each literal (save for the last)
+5
source share

A cleaner way to do it.

Create a class variable:

 private static final String BLANK_SPACE=" "; 

Now in your StringBuilder code, add it if necessary:

 StringBuilder builder = new StringBuilder(); builder.append("watch"); builder.append(BLANK_SPACE); builder.append("on"); builder.append("youtube"); builder.append(":"); builder.append(BLANK_SPACE); builder.append("Mickey"); builder.append("en"); builder.append("de"); builder.append(BLANK_SPACE); builder.append("stomende"); builder.append("drol"); System.out.println(builder.toString()); 
+1
source share

A simple string containing a single space character is simple .

So, you can add it in the same way as adding any other line.

  StringBuilder builder = new StringBuilder(); builder.append("watch"); builder.append(" "); builder.append("on"); builder.append(" "); // and so on 

Remember also that the append method returns a StringBuilder, so you can join applications one by one by following

  StringBuilder builder = new StringBuilder(); builder.append("watch").append(" "); builder.append("on").append(" "); // and so on 
+1
source share

All Articles