1

I have a string "name" which I need to add n amount of blank spaces to the end. I have been told to use String.format but for the life of me I cant figure out how to do it.

String formatName = String.format(name, %15s);
return formatName;

But this didn't work, can anyone point me in the right the direction?

Basically I need to make each string 15 characters long with blank spaces appended to the end if the original string is too short.

================

With advice I reversed the paramaters however this throws up an error.

private String format(String name, String number) 
{
    String formatName = String.format(%15s, name);
    String formatNumber = String.format(%15s, number);
    return formatName + " - " + formatNumber;
}

However this throws an error - Illegal start of expression.

Can anyone tell me what I'm doing wrong?

4
  • 2
    You've got your parameters backwards. Look at the API for java.util.Formatter for more details. Commented Oct 27, 2012 at 20:13
  • 1
    formatName = String.format("%-15s", name). Commented Oct 27, 2012 at 20:13
  • @aioobe nice, didn't know that one, but that does not add n spaces to the end, it pads it until the string is n characters. Chris, is this what was required or did you really require precisely n spaces? Commented Oct 27, 2012 at 20:21
  • @Chris, the format string needs to be between quotes like "%-15s" Commented Oct 27, 2012 at 20:23

1 Answer 1

2
formatName = String.format(name + "%15s", "");

OR

formatName = String.format("%-15s", name);

The - appends to the end of the argument.

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

Comments

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.