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>
", 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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…