且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C 格式的字符串 - 如何使用 sprintf 向字符串值添加前导零?

更新时间:2022-10-23 12:34:59

如何使用 sprintf 向字符串值添加前导零?

使用 "%0*d%s" 在前面加上零.

"%0*d" --> 0 零的最小宽度,* 从参数列表导出的宽度,d 打印一个 int.

字符串前面不需要零时,需要一个异常.

void PrependZeros(char *dest, const char *src, unsigned width) {size_t len = strlen(src);if (len >= width) strcpy(dest, src);else sprintf(dest, "%0*d%s", (int) (width - len), 0, src);}

但我不认为 sprintf() 是适合这项工作的工具,代码如下.

//根据需要在前面加上0",从而产生一个 _minimal_ 宽度的字符串.void PrependZeros(char *dest, const char *src, unsigned minimum_width) {size_t len = strlen(src);size_t zeros = (len > minimum_width) ?0 : minimum_width - len;memset(dest, '0', 零);strcpy(dest + zeros, src);}

void testw(const char *src, unsigned width) {字符 dest[100];PrependZeros(dest, src, width);printf("%u \n", width, dest);}int main() {for (无符号 w = 0; w 

输出

0 1 <你好>2 <你好>3 <你好>4 <你好>5 <你好>6 <0你好>7 <00你好>8 <000你好>9 <0000你好>0 <>1<0>

I want to add zeroes at the starting of a string. I am using format specifier. My input string is hello I want output as 000hello.

I know how to do this for integer.

int main()
{
    int i=232;
    char str[21];
    sprintf(str,"%08d",i);

    printf("%s",str);

    return 0;
}

OUTPUT will be -- 00000232

If I do the same for string.

 int main()
    {
        char i[]="hello";
        char str[21];
        sprintf(str,"%08s",i);

        printf("%s",str);

        return 0;
    }

OUTPUT will be - hello (with 3 leading space)

Why it is giving space in case of string and zero in case of integer?

How to add leading zeros to string value using sprintf?

Use "%0*d%s" to prepend zeros.

"%0*d" --> 0 min width of zeros, * derived width from the argument list, d print an int.

An exception is needed when the string needs no zeros up front.

void PrependZeros(char *dest, const char *src, unsigned width) {
  size_t len = strlen(src);
  if (len >= width) strcpy(dest, src);
  else sprintf(dest, "%0*d%s", (int) (width - len), 0, src);
}


Yet I do not think sprintf() is the right tool for the job and would code as below.

// prepend "0" as needed resulting in a string of _minimal_ width.
void PrependZeros(char *dest, const char *src, unsigned minimal_width) {
  size_t len = strlen(src);
  size_t zeros = (len > minimal_width) ? 0 : minimal_width - len;
  memset(dest, '0', zeros);
  strcpy(dest + zeros, src);
}


void testw(const char *src, unsigned width) {
  char dest[100];
  PrependZeros(dest, src, width);
  printf("%u <%s>\n", width, dest);
}

int main() {
  for (unsigned w = 0; w < 10; w++)
    testw("Hello", w);
  for (unsigned w = 0; w < 2; w++)
    testw("", w);
}

Output

0 <Hello>
1 <Hello>
2 <Hello>
3 <Hello>
4 <Hello>
5 <Hello>
6 <0Hello>
7 <00Hello>
8 <000Hello>
9 <0000Hello>
0 <>
1 <0>