Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is String.Format("%1s","") not returning "" but " "?

Tags:

java

string

String.format("%1s","").equals("")); // --> return false !
String.format("%1s","").equals(" ")); // --> return true !
  • Why is this happening ?
  • Where does the space come from ?
like image 995
C4stor Avatar asked Mar 06 '14 16:03

C4stor


2 Answers

The space is specified by the minimum width value 1 in the format specifier

String.format("%1s","").equals(" ")
                ^
like image 121
Reimeus Avatar answered Sep 22 '22 11:09

Reimeus


You wanted to add an argument index like this

String.format("%1$s", ""); //returns ""
String.format("%2$s %1$s", "a", "b"); //returns "b a"

Your code defined a "width"

String.format("%3s", ""); // returns "   ";
String.format("%3s", "a"); // returns "  a";
String.format("%-3s", "a"); // returns "a  ";

Read this for more info: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

like image 37
Mathias Begert Avatar answered Sep 22 '22 11:09

Mathias Begert