Problem

You know what, left pad is javascript package and referenced by React:
Github link

One day his author unpublished it, then a lot of javascript projects in the world broken.

You can see from github it's only 11 lines.

You job is to implement the left pad function. If you do not know what left pad does, see examples below and guess.

Example

leftpad("foo", 5)
 "  foo"

leftpad("foobar", 6)
 "foobar"

leftpad("1", 2, "0")
 "01"

Note

就是两个method,一个有参数padChar,一个没有,做法一样。用" "padChar放入originalStr前缀,直到新的字符串长度等于size

Solution

public class StringUtils {
    static public String leftPad(String originalStr, int size) {
        int len = originalStr.length();
        StringBuilder sb = new StringBuilder();

        if (size <= len) return originalStr;
        else {
            for (int i = 0; i < size-len; i++) sb.append(" ");
            sb.append(originalStr);
        }
        return sb.toString();
    }
    static public String leftPad(String originalStr, int size, char padChar) {
        int len = originalStr.length();
        StringBuilder sb = new StringBuilder();

        if (size <= len) return originalStr;
        else {
            for (int i = 0; i < size-len; i++) sb.append(padChar);
            sb.append(originalStr);
        }
        return sb.toString();
    }
}

linspiration
161 声望53 粉丝