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 instance variables from the class it would be defined in. It's declared public only because it might be generally useful.
Example
| Call | Returns | Comments |
|---|---|---|
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, is to loop adding blanks to the left until the string is long enough. The reason this isn't efficient for a large amount of padding is that each time thru the loop creates a new String object.
Assumptions
Write only the method. You do not need to write a class or test program.















