Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding printf for Strings by 0

Tags:

c

printf

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!!

like image 483
Akash Avatar asked Jan 13 '12 17:01

Akash


People also ask

How do I print a string of 0?

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.

How do I add padding to printf?

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".

How to pad leading zeros in java?

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.

What is string padding in C?

@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.


2 Answers

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;
}
like image 134
zwol Avatar answered Oct 10 '22 18:10

zwol


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
like image 43
mvgucht Avatar answered Oct 10 '22 18:10

mvgucht