Is there a way to replace the space character to 0 in printf padding for field width
Code used
printf("%010s","this");
Doesnt seem to work for strings!!
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character.
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following. char *ptr = "Hello"; printf("%40s\n", ptr); That will give you 35 spaces, then the word "Hello".
Left and Right padding Integer and String in Java You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
@litb, strncpy: If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
Indeed, the 0
flag only works for numeric conversions. You will have to do this by hand:
int print_padleftzeroes(const char *s, size_t width)
{
size_t n = strlen(s);
if(width < n)
return -1;
while(width > n)
{
putchar('0');
width--;
}
fputs(s, stdout);
return 0;
}
what about
test="ABCD"
printf "%0$(expr 9 - ${#test})d%s" 0 $test
that will give you what you need too.
~:00000ABCD
or is you want to padd with other numbers just change
printf "%0$(expr 9 - ${#test})d%s" 1 $test
will give you
~:11111ABCD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With