1

I know we can left-pad integers with a formatter like this:

String.format("%7d", 234);   // "    234"
String.format("%07d", 234);  // "0000234"
String.format("%015d", 234); // "0000000000000234"

But, how to replace the zeros by dots (like a plain text content index)?

String.format("%.13d", 234); // doesn't work

I want to produce this:

..........234

I know I can use a loop to add the dots, but I want to know if there is a way to do this with a formatter.

Martijn Courteaux
  • 63,780
  • 43
  • 187
  • 279

4 Answers4

3

I think there is no such . padding build in, but you can pad with spaces and then replace them.

 String.format("%15d", 234).replaceAll(' ', '.');
Paŭlo Ebermann
  • 68,531
  • 18
  • 138
  • 203
1

There's no way to do with with the formatter alone, but

String.format("%015d", 234).replaceFirst("0*","\.");

should do just fine.

(Naturally, you have to then do something with the string -- this one produces a String object which then disappears, since this doesn't assign to anything.)

Update

Damn, forgot the repeat * in the regex.

Charlie Martin
  • 103,438
  • 22
  • 180
  • 253
  • 2
    @Martijn, you'll probably find in the future that saying what error you think you've found will serve you well. – Charlie Martin May 30 '11 at 21:34
  • The errors, I found without compiling are: 1) All the zeros will be replaced by one single dot. 2) `"\."` is an non-existing escape character. So, if you meant `\\.`, it won't be replaced by a dot but with literally `\.`. – Martijn Courteaux May 31 '11 at 15:04
1

Another way to do this is to use the Apache Commons Lang lib. http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#leftPad%28java.lang.String,%20int,%20char%29

grundprinzip already pointed that out...

pogopaule
  • 1,433
  • 1
  • 9
  • 17
0

You can do it manually. It is not beautiful but it works.

String str = Integer.toString( 234 );
str = "...............".substring( 0, Math.max( 0, 15 - str.length() ) ) + str;
x4u
  • 13,091
  • 5
  • 45
  • 55