Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way of left padding a string with zeroes [duplicate]

Tags:

java

string

This is how I left pad a string with zeroes:

String.format("%16s", cardTypeString.trim()).replace(' ', '0');

Is there a better way to do this? I don't like the .replace(' ', '0') part.

like image 498
Blair Osbay Avatar asked Apr 21 '16 05:04

Blair Osbay


2 Answers

You may use StringUtils from Apache Commons:

StringUtils.leftPad(cardTypeString, 16, '0');
like image 174
Yevhen Surovskyi Avatar answered Oct 23 '22 10:10

Yevhen Surovskyi


Implement you own PadLeft:

public static String padLeft(String value, int width, char pad) {
    if (value.length() >= width)
        return value;
    char[] buf = new char[width];
    int padLen = width - value.length();
    Arrays.fill(buf, 0, padLen, pad);
    value.getChars(0, value.length(), buf, padLen);
    return new String(buf);
}

See IDEONE demo.

like image 40
Andreas Avatar answered Oct 23 '22 11:10

Andreas