题目三十二:
实现一个leftpad库,如果不知道什么是leftpad可以看样例
样例
leftpad("foo", 5)
>> " foo"
leftpad("foobar", 6)
>> "foobar"
leftpad("1", 2, "0")
>> "01"
代码:
class StringUtils {
public:
/*
* @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 string leftPad(string &originalStr, int size, char padChar=' ') {
// write your code here
int siz = originalStr.length();
if(siz>=size)
return originalStr;
else
{
siz = size - originalStr.length();
char a[siz+1];
for(int i=0;i<siz;i++)
a[i]=padChar;
a[siz]='\0';
string b=a;
originalStr = b+originalStr;
return originalStr;
}
}
};
思路:用于填充的字符数组添加终止符‘\0’不然是无法accepted的