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 do开发者_开发百科ts, but I want to know if there is a way to do this with a formatter.
I think there is no such .
padding build in, but you can pad with spaces and then replace them.
String.format("%15d", 234).replaceAll(' ', '.');
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...
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.
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;
精彩评论