Search code examples
cprintfcenteringstdio

How do I print center aligned string in C


Can anyone help me in printing the string aligned to center in C?

For example:

int main()
{
    int a = 20;
    char x[10] = "Hello";
    char y[10] = "Hello";
    printf ("%*s\n",a, x );
    printf ("%-*s\n",a,y);
}

In the above the first prints Hello aligned to the right and the second printf to the left like this

                    Hello
Hello  

restricting the length for each to 20.

Is there a way to print Hello aligned to the center.

        Hello              

restricting the total length to 20.

Thankyou in advance


Solution

  • In general, you probably want to avoid centre-aligned text, especially on a console, but in any case; this will take some doing.

    The (likely) reason that printf doesn't know how to do this to begin with is that it's not an entirely deterministic operation; not all strings can be centred in all spaces.

    Notably, unless space_for_string - strlen(string) is an even number, you're going to have to make a choice regarding where you want the string to be shifted to.

    In any case, you do want to use the "%*s"specifier, but the number you feed into the width field can't be as simple as a flat 20.

    Instead you want to feed it half the width of your space plus half the width of your string.

    int main()
    {
      int space = 20;
      char *string = "Hello";
      printf ("%*s\n", space / 2 + strlen(string) / 2,string);
    }