bircastri
bircastri

Reputation: 2167

How to use String.format() in java

I want to create a string in java with a prefix Size like this

String x = "PIPPO                "; //21 character

How can I obtain a string with a prefix size and the other character is space?

I have build this code but I have an error

String ragioneSociale =String.format("%21c%n", myString);

Upvotes: 2

Views: 963

Answers (3)

Jens
Jens

Reputation: 69440

Message you get is

Exception in thread "main" java.util.IllegalFormatConversionException: c != java.lang.String

Because "c" is the format specification for character.

You have to use "s" because you want a string:

String ragioneSociale =String.format("%-21s%n", myString);

And because you want it left aligned, you have to add a minus sign.

For more informations see the documentation of Formatter.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140447

Here:

String ragioneSociale =String.format("%21c%n", myString);

The c is the wrong format specifier. You want: s instead. From javadoc:

's', 'S' general If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

'c', 'C' character The result is a Unicode character

And as the argument you are providing is a String, not a character c can't work.

And for the aligning with spaces; go for "%1$-21s" as format instead.

Upvotes: 1

Laurent Grousset
Laurent Grousset

Reputation: 403

You can right pad your String ?

String x = "PIPPO";
String xRightPadded = String.format("%1$-21s", x);

more informations can be found here : How can I pad a String in Java?

Upvotes: 4

Related Questions