Java: Exercise - Pad Left

Problem

Write a method to return a string which is the parameter with add extra blanks to the left end to make it length width. If the string is already width characters or longer, no padding should be performed.

Signature

    public static String padLeft(String s, int width)
Note: This is declared static because it is doesn't depend on any instance variables from the class it would be defined in. It's declared public only because it might be generally useful.

Example

CallReturnsComments
padLeft("Hello", 8)"   Hello"Three blanks added.
padLeft("Hello", 2)"Hello"No blanks added; the string is already longer than width.
padLeft("", 4)"    "Four blanks total.
padLeft("2", 5)"    2"Four blanks added.

Hint

The simplest, but not the most efficient, it to loop adding blanks to the left until the string is long enuf. The reason this wouldn't be efficient for a large amount of padding is that each time thru the loop would create a new String object.

Assumptions

Write only the method. You can easily change the Example - Generic Calc program to use this method.