Reputation: 199225
I know I can fill with spaces using :
String.format("%6s", "abc"); // ___abc ( three spaces before abc
But I can't seem to find how to produce:
000abc
Edit:
I tried %06s
prior to asking this. Just letting you know before more ( untried ) answers show up.
Currently I have: String.format("%6s", data ).replace(' ', '0' )
But I think there must exists a better way.
Upvotes: 6
Views: 3182
Reputation: 15690
By all means, find a library you like for this kind of stuff and learn what's in your shiny new toolbox so you reinvent fewer wheels (that sometimes have flats). I prefer Guava to Apache Commons. In this case they are equivalent:
Strings.padStart("abc",6,'0');
Upvotes: 1
Reputation: 44240
Try rolling your own static-utility method
public static String leftPadStringWithChar(String s, int fixedLength, char c){
if(fixedLength < s.length()){
throw new IllegalArgumentException();
}
StringBuilder sb = new StringBuilder(s);
for(int i = 0; i < fixedLength - s.length(); i++){
sb.insert(0, c);
}
return sb.toString();
}
And then use it, as such
System.out.println(leftPadStringWithChar("abc", 6, '0'));
OUTPUT
000abc
Upvotes: 1
Reputation: 75906
Quick and dirty (set the length of the "000....00" string as the maximum len you support) :
public static String lefTpadWithZeros(String x,int minlen) {
return x.length()<minlen ?
"000000000000000".substring(0,minlen-x.length()) + x : x;
}
Upvotes: 0
Reputation: 22070
You should really consider using StringUtils from Apache Commons Lang for such String manipulation tasks as your code will get much more readable. Your example would be StringUtils.leftPad("abc", 6, ' ');
Upvotes: 7
Reputation: 3826
I think this is what you're looking for.
String.format("%06s", "abc");
Upvotes: -1