Fill lines with 0 using formatter

I know I can fill in the blanks using:

String.format("%6s", "abc"); // ___abc ( three spaces before abc

But I can not find how to produce:

000abc

Edit:

I tried %06sbefore asking this. Just let you know before new (inexperienced) answers come up.

Currently I have: String.format("%6s", data ).replace(' ', '0' )But I think there must be a better way.

+5
source share
5 answers

You should consider using StringUtils in Apache Commons Lang for such string manipulation tasks, as your code will become much more readable. Your example will beStringUtils.leftPad("abc", 6, ' ');

+5
source

Try running your own static 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();
}

,

System.out.println(leftPadStringWithChar("abc", 6, '0'));

OUTPUT

000abc
+1

, , , , , ( ). Guava Apache Commons. :

Strings.padStart("abc",6,'0');
+1

( "000.... 00" , ):

public static String lefTpadWithZeros(String x,int minlen) {
   return x.length()<minlen ? 
       "000000000000000".substring(0,minlen-x.length()) + x : x;     
}
0

, , .

String.format("%06s", "abc");
-1

All Articles