Frage

Suppose I want to add some space between two strings, if I know the amount of space to be added to be 10 (at compiletime) I can do this:

String s = String.format("%-10s %s", "Hello", "World");

But what if I don't know that it is 10, if I have to figure it out at runtime?

int space = new java.util.Random().nextInt(n);
String s = String.format("-???%s %s, "Hello", "World");

I am aware I can concatenate

String.format("%-" + space + "s %s";, "Hello", "World"));

But it feels like a dirty hack. Is there a less hacky way of specifying the argument at runtime? Formatter is of little help. I know better and more efficient ways of manipulating the strings but am curious if it is possible with String.format without the hack.

War es hilfreich?

Lösung

It's not really a dirty hack. The String.format() function expects a String defining the format. If that String is something you have to generate at run-time, then it is acceptable to use whatever means necessary to do that, even if it is another call to String.format(). It would make your code a bit clearer, IMO, to store the format string in a separate variable instead of nesting the calls:

int width = ...;
String fmt = String.format("-%i%%s %%s", width);
String formatted = String.format(fmt, "Hello", "World");

As opposed to:

int width = ...;
String formatted = String.format(String.format("-%i%%s %%s", width), "Hello", "World");

The former is clear and fairly self-documenting. You could also just construct the string with concatenation, if that suits your fancy, ahead of time or inline:

int width = ...;
String fmt = "-" + width + "%s %s";
String formatted = String.format(fmt, "Hello", "World");

Or:

int width = ...;
String formatted = String.format("-" + width + "%s %s", "Hello", "World");

That also looks pretty clear to me. Whether you do it inline or ahead of time really depends on personal preference; for more complex formatting strings the difference may be more apparent.

Adding an explanatory comment takes care of any confusion, and is probably the most important thing you can do to clear up your code.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top