简体   繁体   中英

How to add padding to left and right of a string in Java

I want to add padding to left and right of my string and print something like:

|          WELCOME TO THE GAME          |

I am trying this:

System.out.printf("|%15s%20s|%n",header,"");

and the output is:

|WELCOME TO THE GAME                    |

I have 2 questions here:

  1. Any better way to do padding both left and right of my keyword without actually using an empty string?
  2. What would be the right formatting to get the desired output?

change it to 30, 10

System.out.printf("|%30s%10s|%n",header,"");

it's output

|           WELCOME TO THE GAME          |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM