题目:
实现一个leftpad库,如果不知道什么是leftpad如下所示:
leftpad("foo", 5)
>> " foo"
leftpad("foobar", 6)
>> "foobar"
leftpad("1", 2, "0")
>> "01"
*实现多重载leftpad() ,表示两种不同需求的展示。
*问题的关键点 长度 和 附加Str的组装。
*长度我们要考虑原Str的Length 和现有Size的差值比较,在合理情况下才可以继续,否则返回false.
*Str的组装,利用Size差值while循环累加Str得到附加Str.
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
*/
public String leftPad(String originalStr, int size)
{
// Write your code here
var strLength = originalStr.Length;
size = size - strLength;
if (size > 0)
{
var innerStr = "";
while (size > 0)
{
innerStr += " ";
size--;
}
return String.Format("{0}{1}", innerStr, originalStr);
}
else
{
return null;
}
}
/**
* @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
*/
public String leftPad(String originalStr, int size, char padChar)
{
// Write your code here
var strLength = originalStr.Length;
size = size - strLength;
if (size > 0)
{
var innerStr = "";
while (size > 0)
{
innerStr += padChar;
size--;
}
return String.Format("{0}{1}", innerStr, originalStr);
}
else
{
return null;
}
}
}