实现一个leftpad库,如果不知道什么是leftpad可以看样例
样例
leftpad("foo", 5)
>> " foo"
leftpad("foobar", 6)
>> "foobar"
leftpad("1", 2, "0")
>> "01"
解题思路:
直接写即可,注意代码的复用。
public class StringUtils {
/**
* @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
if(originalStr == null || originalStr.length() == 0)
return "";
int len = originalStr.length();
int cnt = size - len;
//如果size比Str长度还小,则无法左填充,返回原Str
if(cnt <= 0)
return originalStr;
StringBuilder res = new StringBuilder(size);
//填充前缀
while(cnt-- != 0)
res.append(padChar);
res.append(originalStr);
return res.toString();
}
}