Left Pad(左填充 )

问题

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"

分析

注意第二个方法代表是左边用padChar来填充,所以第一个方法是第二个方法特殊情况,注意调用关系。

代码

    /**
     * @param originalStr the string we want to append to with spaces
     * @param size the target length of the string
     * @return a string
     */
    static public String leftPad(String originalStr, int size) {
        // Write your code here
        return leftPad(originalStr,size,' ');
    }

    /**
     * @param originalStr the string we want to append to
     * @param size the target length of the string
     * @param padChar the character to pad to the left side of the string
     * @return a string
     */
    static public String leftPad(String originalStr, int size, char padChar) {
        // Write your code here
        int len=size-originalStr.length();
        StringBuilder sb=new StringBuilder();
        while(len>0){
            sb.append(padChar);
            len--;
        }
        sb.append(originalStr);
        return sb.toString();
    }
}

你可能感兴趣的:(Left Pad(左填充 ))