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.
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, ' ');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With