Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format() adding 2 blank spaces when arguments are empty strings

I have this simple method that goes:

private String toJsonFormat(String name, Object value, boolean first) {
    value = value == null ? "" : value; 
    return String.format((first ? "" : ",") + "\"%1s\":\"%2s\"", name, value);
}

When my value argument is null, 2 blank spaces are added after the colon, instead of an empty string.

An example return value when null is passed:

"housenumber":"  "

How come?

like image 500
Pearl Jade Avatar asked Apr 26 '26 00:04

Pearl Jade


1 Answers

The format specifier

%2s

means that this field will be at least two characters wide, space-padded as necessary.

If what you meant is "the second string", then just write

%s

This will automatically give you the second argument because it is the second specifier you use. Same for %1s you have for the first argument.

like image 177
Marko Topolnik Avatar answered Apr 28 '26 14:04

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!