如何在Java中使用String.format()复制选项卡“\t”? [英] How to use String.format() in Java to replicate tab "\t"?
问题描述
我最初使用的是 我打印的数据是一行一行的,希望它像表格一样组织。 + lastName +\ t+ phoneNumber firstName +,
。
但是对于一些较大的名字, / p>
我试图使用String.format()来达到这个效果。任何人都可以告诉我使用的格式语法?
我试过 String.format(%s,%s,%20s,firstName, lastName,phoneNumber)
,但这不是我想要的。我希望它看起来像这样:
John,Smith 123456789
Bob,Madison 123456789
Charles,Richards 123456789
编辑:
这些答案似乎适用于System.out.println()。但我需要它为JTextArea工作。我正在使用textArea.setText()
解决了这个问题。 JTextArea默认不使用等宽字体。我用setFont()来改变它,现在它像一个魅力。感谢所有的解决方案。
考虑使用负数来表示长度说明符:% - 20S
。例如:
pre $ public static void main(String [] args){
String [] firstNames = {Pete ,乔恩,弗雷德};
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);
$ p $ return $
Klein,Pete 555-123-4567
Jones,Jon 555-123-4567
Flinstone,Fred 555-123-4567
I'm printing data line by line and want it to be organized like a table.
I initially used firstName + ", " + lastName + "\t" + phoneNumber
.
But for some of the larger names, the phone number gets pushed out of alignment
I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?
I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber)
, but that's not what I want. I want it to look like this:
John, Smith 123456789
Bob, Madison 123456789
Charles, Richards 123456789
Edit: These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()
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.
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);
}
}
returns
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
这篇关于如何在Java中使用String.format()复制选项卡“\t”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!