问题
How can I format a string of text, like givenname, surname, telephone etc to look like columns?
this won't do it:
String customer = "\t"+surname+"\t"+givenname+"\t"+blablabla
回答1:
See the documentation for String.format(). Use maximum length each column can be, plus 1.
回答2:
The problem with using tab characters is that their width is dependent on the settings of the console you're using for display, which means you can't guarantee that all columns will line up using this approach.
Assuming you're formatting the text to a console using a monospaced font, you could use single space characters to pad each string. To accomplish this you'll need to know the maximum length of each string field for a given column.
回答3:
There are some libraries in the wild wild web that can do that for you - with the general limitation that it usually will work with monospaced fonts (like Courier). One of those libraries is the iNamik Text Table Formatter for Java, but if you use google to look for java text table you'll find a lot more.
来源:https://stackoverflow.com/questions/1519260/java-text-formatting