String.format()填充字符串? [英] String.format() to fill a string?

查看:1309
本文介绍了String.format()填充字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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:

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?

谢谢

推荐答案

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

打印:

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

关键表达式为:

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

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

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

可选地,因为前缀不包含任何空格在这种特殊情况下,您可以将牛带入:

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(' ', '-')



参见




  • java.util.Formatter - 完整格式化语法

  • 这篇关于String.format()填充字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆