字符串的 Java 输出格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4418308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:16:02  来源:igfitidea点击:

Java output formatting for Strings

javaformatting

提问by Steffan Harris

I was wondering if someone can show me how to use the format method for Java Strings. For instance If I want the width of all my output to be the same

我想知道是否有人可以告诉我如何使用 Java 字符串的格式方法。例如,如果我希望所有输出的宽度相同

For instance, Suppose I always want my output to be the same

例如,假设我总是希望我的输出相同

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.

在这个例子中,所有的输出都整齐地排列在彼此之下;我将如何使用 format 方法完成此操作。

采纳答案by gnomed

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

编辑:这是一个非常原始的答案,但我无法删除它,因为它已被接受。请参阅下面的答案以获得更好的解决方案

Why not just generate a whitespace string dynamically to insert into the statement.

为什么不直接生成一个空白字符串来插入到语句中。

So if you want them all to start on the 50th character...

所以如果你想让它们都从第 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);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilderclass too which is more efficient.

将所有这些放在一个循环中,并在每次迭代之前初始化/设置“键”和“值”变量,你就很成功了。我也会使用StringBuilder更有效的类。

回答by I82Much

If you want a minimum of 4 characters, for instance,

例如,如果您想要至少 4 个字符,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

回答by stacker

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string
  • 其中 %s 是您字符串的占位符。
  • '-' 使结果左对齐。
  • 20 是第一个字符串的宽度

The output looks like this:

输出如下所示:

label               = content

As a reference I recommend Javadoc on formatter syntax

作为参考,我推荐关于格式化程序语法的 Javadoc

回答by Peter Lawrey

To answer your updated question you can do

要回答您更新的问题,您可以这样做

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]);
}

prints

印刷

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

回答by Roman

For decimal values you can use DecimalFormat

对于十进制值,您可以使用 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);  
   }
}

and output will be:

输出将是:

123456.789  ###,###.###   123,456.789
123456.789  ###.##        123456.79
123.78      000000.000    000123.780
12345.67    $###,###.###  ,345.67

For more details look here:

更多详情请看这里:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

回答by Amol Kakade

     @Override
     public String toString() {
          return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
     }