简体   繁体   中英

how can I use string.format() to right justify a string within three characters?

   | -1|  0|  1|  2|
   +---+---+---+---+
-2 | hi| hi| hi| hi|
   +---+---+---+---+
-1 | hi| hi| hi| hi|
   +---+---+---+---+

There is a chessboard with numberings on the first row and first column. Each cell can hold a string less than three characters and each string is right justified. So how can I use string.format() to right justify a string? Even though like "hi" is a two-character string, I still want a three-character cell, how can I make it? I am not very familiar with string.format()

To justify a String You can try this:

System.out.println( "%-3s %3s %n", NAME1, NAME2);

To get the left-justified column, a minus symbol, the number of characters,. So ''%-3s'' means 3 characters left-justified.

To get a right-justified column delete the minus sign.

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