2

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);
Manos Nikolaidis
  • 18,967
  • 11
  • 60
  • 72
bircastri
  • 2,707
  • 7
  • 38
  • 96
  • 1
    It'd be useful if you read the Formatter documentation and mention what error you get – OneCricketeer May 11 '17 at 11:14
  • 1
    @CraigR8806 Because it is bad practice to re-invent the wheel when the standard APIs already implement a generic, well-tested, robust solution? – GhostCat May 11 '17 at 11:16

3 Answers3

4

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?

Community
  • 1
  • 1
  • I was too lazy to check the padding part of the format; so my vote goes to your quick answer on that! – GhostCat May 11 '17 at 11:23
  • Can you explain what `%1$` means? At least a Minium of Explanation will be helpful – Jens May 11 '17 at 11:40
  • @Jens : you can refer to http://stackoverflow.com/questions/5762836/what-does-1-mean-when-used-in-string-format-java , this is the argument_index – Laurent Grousset May 11 '17 at 13:04
1

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.

Jens
  • 60,806
  • 15
  • 81
  • 95
1

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.

Community
  • 1
  • 1
GhostCat
  • 127,190
  • 21
  • 146
  • 218
  • I have used your code and I have change c whit s, but now I have this " PIPPO" intead I want the the blank space is after string – bircastri May 11 '17 at 11:21
  • See my updated answer; or the other one that gave you the correct pattern as well. – GhostCat May 11 '17 at 11:22