C4stor
C4stor

Reputation: 8036

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

String.format("%1s","").equals("")); // --> return false !
String.format("%1s","").equals(" ")); // --> return true !

Upvotes: 6

Views: 11106

Answers (3)

Reimeus
Reimeus

Reputation: 159844

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

String.format("%1s","").equals(" ")
                ^

Upvotes: 13

jagmohan
jagmohan

Reputation: 2052

Here %1s is a format specifier which doesn't have any arguments. The general syntax for no argument format specifier is as follows

%[flags][width]conversion

where

The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

and

The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

So, 1 specifies the width and here is the description behind why you get " " and not ""

The width is the minimum number of characters to be written to the output. If the length of the converted value is less than the width then the output will be padded by ' ' (\u0020') until the total number of characters equals the width. The padding is on the left by default. If the '-' flag is given, then the padding will be on the right. If the width is not specified then there is no minimum.

PS: \u0020 is Unicode character for Space.

Hope this helps.

Upvotes: 1

Mathias Begert
Mathias Begert

Reputation: 2470

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

Upvotes: 3

Related Questions