您的位置:首页 > 其它

lintcode: 左填充

2016-07-07 14:56 375 查看
[b]题目[/b]


实现一个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
int n = originalStr.length();
if(n>=size)
return originalStr;
int k = size - n;
StringBuffer newStr = new StringBuffer();
while(k>=1){
newStr.append(' ');
k--;
}
newStr.append(originalStr);
return newStr.toString();
}

/**
* @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 n = originalStr.length();
if(n>=size)
return originalStr;
int k = size - n;
StringBuffer newStr = new StringBuffer();
while(k>=1){
newStr.append(padChar);
k--;
}
newStr.append(originalStr);
return newStr.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: