[英]Java output formatting for Strings
我想知道是否有人可以告訴我如何使用 Java 字符串的格式方法。 例如,如果我希望所有輸出的寬度相同
例如,假設我總是希望我的輸出相同
Name = Bob
Age = 27
Occupation = Student
Status = Single
在這個例子中,所有的輸出都整齊地排列在彼此之下; 我將如何使用 format 方法完成此操作。
System.out.println(String.format("%-20s= %s" , "label", "content" ));
輸出如下所示:
label = content
作為參考,我推薦關於格式化程序語法的 Javadoc
例如,如果您想要至少 4 個字符,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
要回答您更新的問題,您可以這樣做
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
印刷
Name = Bob
Age = 27
Occupation = Student
Status = Single
為什么不直接生成一個空白字符串來插入到語句中。
所以如果你想讓它們都從第 50 個字符開始......
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
將所有這些放在一個循環中,並在每次迭代之前初始化/設置“鍵”和“值”變量,你就很成功了。 我也會使用StringBuilder
類,它更有效。
@Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
對於十進制值,您可以使用 DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
輸出將是:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
更多詳情請看這里:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.