Java 如何使用 printf() 和可变宽度将字符串输出居中?[爪哇]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2709993/
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-13 11:07:39  来源:igfitidea点击:

How to center string output using printf() and variable width? [java]

javaprintf

提问by Khan

I'm creating an output in Java using printf() to create table headers. One of the columns needs variable width.

我正在使用 printf() 在 Java 中创建一个输出来创建表头。其中一列需要可变宽度。

Basically it should look like this:

基本上它应该是这样的:

//two coords
Trial    Column Heading
1        (20,30)(30,20)
//three coords
Trial        Column Heading
1        (20,40)(50,10)(90,30)

I tried to use:

我尝试使用:

int spacing = numCoords * 7; //size of column
printf("Trial    %*^s", column, "Column Heading");

But I keep getting output errors when I try to use * or ^ in the conversion statement.

但是当我尝试在转换语句中使用 * 或 ^ 时,我不断收到输出错误。

Does anyone have any idea what the correct formatting string should be?

有谁知道正确的格式字符串应该是什么?

采纳答案by Behrang Saeedzadeh

Use StringUtils.center from the Commons Lang library:

使用Commons Lang 库中的StringUtils.center :

StringUtils.center(column, "Column Heading".length());

回答by Brett Kail

Java does not support the "*" format specifier. Instead, insert the width directly into the format string:

Java 不支持“*”格式说明符。相反,将宽度直接插入格式字符串:

int spacing = numCoords * 7; //size of column
System.out.printf("Trial    %" + spacing + "s", "Column Heading");