C formatted string - How to add leading zeros to s

2019-09-21 10:30发布

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?

2条回答
何必那么认真
2楼-- · 2019-09-21 11:11

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>
查看更多
爷、活的狠高调
3楼-- · 2019-09-21 11:30
void left_fill_zeros(char* dest, const char* str, int length)
{
    sprintf(dest, "%.*d%s", (int)(length-strlen(str)), 0, str);
}

int main(void)
{
    char output[256];
    left_fill_zeros(output, "Hello", 10);
    puts(output);

    // Total length will be 10 chars
    // Output will be: "00000Hello"
    return 0;
}
查看更多
登录 后发表回答