如何在 Java 中使用 String.format() 来复制选项卡“ "?

2022-01-09 00:00:00 format syntax tabs java

我正在逐行打印数据,并希望它像表格一样组织.

I'm printing data line by line and want it to be organized like a table.

我最初使用 firstName + ", " + lastName + " " + phoneNumber.

但是对于一些较大的名字,电话号码会被推到不对齐

But for some of the larger names, the phone number gets pushed out of alignment

我正在尝试使用 String.format() 来实现此效果.谁能告诉我要使用的格式语法吗?

I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?

我试过 String.format("%s, %s, %20s", firstName, lastName, phoneNumber),但这不是我想要的.我希望它看起来像这样:

I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber), but that's not what I want. I want it to look like this:

约翰·史密斯            123456789

John, Smith            123456789

鲍勃,麦迪逊         123456789

Bob, Madison         123456789

查尔斯·理查兹  123456789

Charles, Richards  123456789

这些答案似乎适用于 System.out.println().但我需要它为 JTextArea 工作.我正在使用 textArea.setText()

These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()

解决了.JTextArea 默认不使用等宽字体.我使用 setFont() 来改变它,现在它就像一个魅力.谢谢大家的解决方案.

Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.

推荐答案

考虑使用负数作为长度说明符:%-20s.例如:

consider using a negative number for your length specifier: %-20s. For example:

   public static void main(String[] args) {
     String[] firstNames = {"Pete", "Jon", "Fred"};
     String[] lastNames = {"Klein", "Jones", "Flinstone"};
     String phoneNumber = "555-123-4567";

      for (int i = 0; i < firstNames.length; i++) {
        String foo = String.format("%-20s %s", lastNames[i] + ", " + 
             firstNames[i], phoneNumber);
        System.out.println(foo);
      }   
   }

返回

Klein, Pete          555-123-4567
Jones, Jon           555-123-4567
Flinstone, Fred      555-123-4567

相关文章