Java printf 使用可变字段大小?

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

Java printf using variable field size?

javastringformattingprintf

提问by paxdiablo

I'm just trying to convert some C code over to Java and I'm having a little trouble with String.printf.

我只是想将一些 C 代码转换为 Java,但在String.printf.

In C, to get a specific width based on a variable, I can use:

在 C 中,要根据变量获得特定宽度,我可以使用:

printf("Current index = %*d\n", sz, index);

and it will format the integer to be a specific size based on sz.

它会将整数格式化为基于sz.

Trying:

试:

System.out.println(String.format("Current index = %*d\n", sz, index));

results in an error since it doesn't like the *.

导致错误,因为它不喜欢*.

I currently have the following kludge:

我目前有以下kludge:

System.out.println(String.format("Current index = %" + sz + "d\n", index));

but I'm hoping there's a slightly better way, yes?

但我希望有更好的方法,是吗?

采纳答案by user1970914

Declare an extra variable before using printf:

在使用之前声明一个额外的变量printf

String format = "%" + fieldSize + "d";
System.out.printf(format, yourVariables);

(this is the first solution I found from a web search)

(这是我从网络搜索中找到的第一个解决方案)

回答by matsev

Presuming that index fits inside sz you can do something like:

假设该索引适合 sz,您可以执行以下操作:

char[] temp = new char[sz];
Arrays.fill(temp, '0');
DecimalFormat df = new DecimalFormat(new String(temp));
System.out.println(String.format("Current index = %s\n", df.format(index))); 

Note, by not using Formator any of its subclasses, there is no Localedependent characters like ' ', '.' or ',' added to the output.

请注意,通过不使用Format或其任何子类,没有Locale像 ' '、'.' 这样的依赖字符。或 ',' 添加到输出中。

回答by Como

This is arguably no better than your "kludge", but here's a method you can embed into the call to printfthat will substitute widths for the asterisks that you pass to it. Its result is used as the real format. For example, consider this call:

这可以说并不比你的“kludge”好,但这里有一个方法你可以嵌入到调用中 printf,它将用宽度替换你传递给它的星号。其结果用作真实格式。例如,考虑这个调用:

System.out.printf("%04d %2s %-7d;%n", 65, "a", 6);

I will replace the first and third widths via an embedded function:

我将通过嵌入式函数替换第一个和第三个宽度:

System.out.printf( wf("%0*d %2s %-*d;%n", 4, 7), 65, "a", 6);

And here's the code:

这是代码:

public static String wf(String fmt, int... widths) {
    return metaWidthFormat('*', fmt, widths);
}

public static String metaWidthFormat(char wmeta, String fmt, int ... widths) {
    if (fmt == null) return null;
    int wix = 0;
    boolean outside = true;
    // initial capacity is sufficient for each substituted width to be 2 digs
    StringBuilder result = new StringBuilder(fmt.length() + widths.length);
    for (char ch : fmt.toCharArray()) {
        if (outside) {
            result.append(ch);
            outside = (ch != '%');
        } else {
            if (ch == wmeta) {
                result.append(widths[wix++]);
            } else {
                result.append(ch);
            }
            outside = (ch == wmeta) || (ch == '%') || Character.isAlphabetic(ch);
        }
    }
    return result.toString();
}

回答by Harsh Gundecha

maybe it's too late but putting it here for others

也许为时已晚,但把它放在这里给其他人

int width = 5;
int precision = 2;
float f = 12.34567f;
System.out.printf("%"+width+"."+precision+"f%n",f);

tested in java 1.8

在 Java 1.8 中测试