5

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
  • 184,433
  • 106
  • 369
  • 548
  • 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

6

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
  • 20,962
  • 8
  • 64
  • 86
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
  • 40,416
  • 33
  • 117
  • 162
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
  • 14,730
  • 3
  • 55
  • 86
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
  • 65,169
  • 19
  • 130
  • 176
-1

I think this is what you're looking for.

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