Example:
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
// 此方法中直接调用另一个版本的method,简单高效。
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.length() >= size) {
return originalStr;
}
int spaceLen = size - originalStr.length();
String result = "";
for (int i = 0; i < spaceLen; i++) {
result = padChar + result;
}
return result + originalStr;
}
}