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);
2
  • 1
    It'd be useful if you read the Formatter documentation and mention what error you get Commented May 11, 2017 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? Commented May 11, 2017 at 11:16

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

3 Comments

I was too lazy to check the padding part of the format; so my vote goes to your quick answer on that!
Can you explain what %1$ means? At least a Minium of Explanation will be helpful
@Jens : you can refer to stackoverflow.com/questions/5762836/… , this is the argument_index
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.

2 Comments

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
See my updated answer; or the other one that gave you the correct pattern as well.
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.

1 Comment

Same thought; you were a bit quicker here ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.