2011-03-04 50 views
0

我必须创建一个具有固定数量字符的字符串。格式说明,如果字符串不够长,字符串必须填上前导空格。将主要空格插入字符串以匹配格式

我如何(优雅地)添加这些领先空间?

P.S.我知道我可以计算字符串的长度和一个空格,直到填满它为止,但是......我觉得这样做会更容易(更优雅)。也许用正则表达式?

+0

应1.1如MSDN页面 – 2011-03-04 23:32:22

+0

[链路上指出所支持到MSDN 1.1页](http://msdn.microsoft.com/en-us/library/system.string.padleft(VS.71).aspx) – 2011-03-04 23:37:38

回答

0

一点点较低的水平,未测试:

 
char * 
padLeft (char *s, size_t size) {   // left-pad s to make a string of size chars 
    char *d = malloc(size + 1); 
    if (d != NULL) { 
    memset(d, ' ', size); 
    strcpy(&d[size - strlen(s)] - 1, s); // copy s (incl '\0'), filling the right part of d 
    } 
    return d; 
}