Atalia.d
Atalia.d

Reputation: 131

How to pad a formatted string

This may seem as a simple problem, but I honestly didn't seem to work this out.
I have a formatted string as follows:

String msg = String.format("Current player: %1$s", status.getCurrentPlayer().getName());

and I want to left-pad it, lets say with 10 spaces. I tried:

String pad = String.format("%1$10s", msg);

but it doesn't seem to work, although I tried it with an unformatted string:

String pad = String.format("%1$10s", "some string");

and obviousely, it worked.
What is it about "msg" that does not let me pad it?

Upvotes: 2

Views: 350

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191728

What is it about "msg" that does not let me pad it?

It's longer than 10 characters.

That 10 is the width of the Formatter class.

Reading that documentation, you'll see

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

So, minimum, meaning any string longer than that are printed as-is.

If you want to pad, just add 10 to the length of the string.

String msg = "some really, really long message";
String fmt = "%1$" + (10 + msg.length()) + "s";
String pad = String.format(fmt, msg);
// "          some really, really long message"

Upvotes: 2

nicomp
nicomp

Reputation: 4647

String msg = "Current player: " 
           + status.getCurrentPlayer().getName() 
           + new String(new char[10]).replace('\0', ' ');

This will add 10 spaces after the name of the player. If you want to take into account the length of the player name you can do this:

String msg = "Current player: " 
             + status.getCurrentPlayer().getName() 
             + new String(new 
                   char[10 - status.getCurrentPlayer().getName().Length ]).replace('\0', ' ');

Upvotes: 2

Related Questions