6

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.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 2
    BTW, I used `%06s` prior to asking this, just letting you know before more ( untried ) answers show up. – OscarRyz May 30 '11 at 19:59

5 Answers5

7

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

Bananeweizen
  • 21,797
  • 8
  • 68
  • 88
1

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
mre
  • 43,520
  • 33
  • 120
  • 170
1

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');
Ed Staub
  • 15,480
  • 3
  • 61
  • 91
0

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;     
}
leonbloy
  • 73,180
  • 20
  • 142
  • 190
-1

I think this is what you're looking for.

String.format("%06s", "abc");
Community
  • 1
  • 1
King Skippus
  • 3,801
  • 1
  • 24
  • 24