Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill strings with 0's using formatter

Tags:

java

formatter

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.

like image 421
OscarRyz Avatar asked May 30 '11 19:05

OscarRyz


2 Answers

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, ' ');

like image 51
Bananeweizen Avatar answered Oct 11 '22 21:10

Bananeweizen


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
like image 29
mre Avatar answered Oct 11 '22 21:10

mre