[LintCode] Left Pad

linspiration

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();
    }
}
阅读 2.7k

Road to Glory
對酒當歌,人生幾何? 譬如朝露,去日苦多。
161 声望
53 粉丝
0 条评论
161 声望
53 粉丝
文章目录
宣传栏