4

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:

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

Justin Ardini
  • 9,768
  • 2
  • 39
  • 46
user246114
  • 50,223
  • 42
  • 112
  • 149
  • 2
    Sidenote: For appending to `Strings` in a loop like you do in your example, you may want to use a `StringBuilder`. – Justin Ardini Aug 10 '10 at 15:51
  • Agreed am using it in my local code just did this for brevity (not that it really saved anything now that I looked at it) – user246114 Aug 10 '10 at 15:53

1 Answers1

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

See also

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • Great, one question - can I supply the format string (the first parameter to format()) as a variable? I know it should be %6d, but can I probably want to compute the value '6', in case I want total length to be 10 or 20 etc. Can I just do String str = "%%" + (fixedlen - "cow".length()) + "d", and supply that as the first param? – user246114 Aug 10 '10 at 15:55
  • @user246114: I think you want `String fmt = "%" + w + "d";` (one `%` only), or possibly `String fmt = String.format("%%%dd", w);`, and then `String.format(fmt, num)`. – polygenelubricants Aug 10 '10 at 15:58
  • CORRECTION: I meant _decimal_ conversion, not _digit_ conversion. Will correct soon. – polygenelubricants Aug 10 '10 at 16:03
  • @user246114: I'm not sure exactly what you're doing, but you may want to look at the width justification formatting example here http://stackoverflow.com/questions/3377688/what-do-these-symbolic-strings-mean-02d-01d/3377719#3377719 ; specifically you can combine left and right justification. – polygenelubricants Aug 10 '10 at 16:19