java String.format() 填充字符串?

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

String.format() to fill a string?

java

提问by user246114

I need to fill a String to a certain length with dashes, like:

我需要用破折号将字符串填充到一定长度,例如:

cow-----8
cow-----9
cow----10
...
cow---100

the total length of the string needs to be 9. The prefix "cow" is constant. I'm iterating up to an input number. I can do this in an ugly way:

字符串的总长度需要为 9。前缀“cow”是常数。我正在迭代一个输入数字。我可以用一种丑陋的方式做到这一点:

String str = "cow";
for (int i = 0; i < 1000; i++) {
    if (i < 10) {
        str += "-----";
    } 
    else if (i < 100) {
        str += "----";
    }
    else if (i < 1000) {
        str += "---";
    }
    else if (i < 10000) {
        str += "--";
    }
    str += i;
}

can I do the same thing more cleanly with string format?

我可以用字符串格式更干净地做同样的事情吗?

Thanks

谢谢

回答by polygenelubricants

    int[] nums = { 1, 12, 123, 1234, 12345, 123456 };
    for (int num : nums) {
        System.out.println("cow" + String.format("%6d", num).replace(' ', '-'));
    }

This prints:

这打印:

cow-----1
cow----12
cow---123
cow--1234
cow-12345
cow123456

The key expression is this:

关键的表达是这样的:

String.format("%6d", num).replace(' ', '-')

This uses String.format, digit conversion, width 6 right justified padding with spaces. We then replaceeach space (if any) with dash.

这使用String.format, 数字转换, 宽度 6 右对齐的空格填充。然后我们replace每个空格(如果有的话)都用破折号。

Optionally, since the prefix doesn't contain any space in this particular case, you can bring the cow in:

或者,由于在这种特殊情况下前缀不包含任何空格,您可以将母牛引入:

String.format("cow%6d", num).replace(' ', '-')

See also

也可以看看