简体   繁体   English

如何在 Java 中为字符串的左右添加填充

[英]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: output 是:

|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?获得所需 output 的正确格式是什么?

change it to 30, 10将其更改为 30、10

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

it's output它是 output

|           WELCOME TO THE GAME          |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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