Best way to leave a space in a string with zeros

This is how I left the pad string with zeros:

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

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

+4
source share
3 answers

You can use StringUtils from Apache Commons :

StringUtils.leftPad(cardTypeString, 16, '0');
+4
source

Implement your 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);
}

Watch the IDEONE demo .

+3
source
// Pad with zeros and a width of 10 chars.
String.format("%1$010d", 245)

See https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html for details

Unfortunately. My fault. This will only work for int, not for String!

0
source

All Articles