By default, printf()
seems to align strings to the right.
printf("%10s %20s %20s\n", "col1", "col2", "col3"); /* col1 col2 col3 */
I can also align text to the left like this:
printf("%-10s %-20s %-20s", "col1", "col2", "col3");
Is there a quick way to center text? Or do I have to write a function that turns a string like test
into (space)(space)test(space)(space)
if the text width for that column is 8?
To center the string for output we use the StringUtils. center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (' ').
You can use the gotoxy() function, like in C++, but in C, it is not pre defined so you should define it first. Another way is to just tab and newline (\t and \n...)
There's no direct way to center text. You'll have to combine several elements: Figure out how many digits you have. Calculate how many spaces you want before and after the number.
printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect)
void f(char *s) { printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,""); } int main(int argc, char **argv) { f("uno"); f("quattro"); return 0; }
@GiuseppeGuerrini's was helpful, by suggesting how to use print format specifiers and dividing the whitespace. Unfortunately, it can truncate text.
The following solves the problem of truncation (assuming the field specified is actually large enough to hold the text).
void centerText(char *text, int fieldWidth) { int padlen = (fieldWidth - strlen(text)) / 2; printf("%*s%s%*s\n", padLen, "", text, padlen, ""); }
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