views:

637

answers:

4

I have tried "&nbsp;&nbsp;" to display two spaces in a standard output Java String. Trying System.out.println("__"); <---- (two spaces, but, obviously, it trims it down to one space, hence the underscore)

I imagine there is a way to escape the &nbsp;, but I can not figure it out nor find help online. Searching for it is ironic because a lot of literal &nbsp;&nbsp; show up.

Any help would be appreciated.

EDIT:

for (int j = 0; j < COLUMNS; j++)
  if (j < 10){
    r += "__";
  }

produces 10 spaces, not 20 like expected when printed

sorry I am still new at formatting here

+7  A: 

&nbsp; is an HTML-specific encoding.

You were right first time - the Java string that corresponds to two spaces is simply two space characters, e.g.

String s = "  ";

The println() call that you tried ought to have worked. What did you do that led you to believe it was trimmed down to a single space? I think your problem is elsewhere...

EDIT:

Based on your code snippet - is COLUMNS 5, by any chance? :-)

EDIT AGAIN:

OK, if COLUMNS is 15 then this code will result in r having twenty spaces appended to it. If you want to be really sure you can either step through in a debugger or put a logging statement above the r += line to see for sure how many times the statement is called.

Also have a look at how r is used later on before its output is printed to the place you're inspecting; perhaps its value is truncated at some point, either explicitly in Java or perhaps even implicitly (such as being stored in a database column that's 10 characters too narrow before being retrieved and displayed later).

Andrzej Doyle
+2  A: 

You don't need to use &nbsp in Java. System.out.print(" "); should do the trick. Try something like:

System.out.print("This is the a string before spaces" + "  " + "this is a string after spaces");
Rocket Surgeon
+1  A: 

If you want a non-breaking space in your string, for whatever reason, you have to use the Unicode literal:

System.out.println("banana\u00A0phone");
Jonathan Feinberg
You don't have to use the unicode literal if your source code character encoding contains a code point for NBSP (and most character encodings does). You can simply use it as any other character directly in the string literal: "banana phone" (no idea how this is actually rendered by SO)
jarnbjo
SO replaced it with a regular space, but as I said, it is possible to use NBSP in Java code.
jarnbjo
You *should* use the unicode literal, so that your intentions regarding an invisible distinction will be made clear.
Jonathan Feinberg
Are you also using the Unicode literal \u006f instead of 'o' to distinguish it from 'о'?
jarnbjo
A: 

You can also create a non-breaking space by holding the Alt key and typing 0160 on the number pad.

Psilokan