字符串的Java输出格式
我想知道是否有人可以向我展示如何对Java字符串使用format方法。例如,如果我希望所有输出的宽度都相同
例如,假设我一直希望我的输出是相同的
Name = Bob
Age = 27
Occupation = Student
Status = Single
在此示例中,所有输出都经过整齐的格式设置; 我将如何使用format方法完成此操作。
6个解决方案
131 votes
System.out.println(String.format("%-20s= %s" , "label", "content" ));
其中%s是您的字符串占位符。
“-”使结果左对齐。
第一个字符串的宽度为20
输出看起来像这样:
label = content
作为参考,我推荐有关格式化程序语法的Javadoc
stacker answered 2020-07-17T14:05:47Z
7 votes
例如,如果您至少需要4个字符,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
I82Much answered 2020-07-17T14:06:06Z
6 votes
编辑:这是一个非常原始的答案,但是我不能删除它,因为它被接受了。 请参阅以下答案,以获得更好的解决方案
为什么不只是动态生成空白字符串以插入到语句中。
因此,如果您希望所有人都从第50个字符开始...
String key = "Name =";
String space = "";
for(int i; i
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
将所有这些放到循环中,并在每次迭代之前初始化/设置“键”和“值”变量,您会很高兴。 我也将使用StringBuilder类,它效率更高。
gnomed answered 2020-07-17T14:05:09Z
6 votes
要回答您更新的问题,您可以执行
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
Peter Lawrey answered 2020-07-17T14:06:30Z
1 votes
@Override
public String toString()
{
return String.format("%15s /n %15d /n %15s /n %15s",name,age,Occupation,status);
}
Amol Kakade answered 2020-07-17T14:06:46Z
0 votes
对于十进制值,可以使用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/Java色/tutorial/Java/data/number format.HTML]
Roman answered 2020-07-17T14:07:19Z