DevelopingDeveloper
DevelopingDeveloper

Reputation: 913

Padding zeros in front of number prefixed by alphabetic string

I have a String, i.e. AB1234. I am trying to create a method I can pass the string into that will always padd zeros in front of the integers to create a 10 digit string.

Some examples:

padZero("AB1234") returns "AB00001234"

padZero("CD001234") returns "CD00001234"

padZero("ABCDEF858") returns "ABCDEF0858"

Is there a simple way to do this without having tons of corner cases you have to try to catch? Assume the case of a String greater than ten digits being passed into this method is caught before the method call.

Upvotes: 1

Views: 109

Answers (3)

sprinter
sprinter

Reputation: 27946

I would think the simplest thing would be to find the first digit and then insert enough zeros to pad to 10 digits:

if (text.matches("\\d")) {
    while (text.length() < 10) {
        text = text.replaceFirst("(\\d)", "0$1");
    }
}

Upvotes: 1

Markus Benko
Markus Benko

Reputation: 1507

Just in case you don't want to make assumptions and instead fail fast on invalid input strings:

private static final Pattern STRING_FORMAT = Pattern.compile("(\\D+)(\\d+)");

public static final String padZeros(String s) {
    Matcher matcher = STRING_FORMAT.matcher(s);
    if (!matcher.matches() || s.length() > 10)
        throw new IllegalArgumentException("Invalid format");
    char[] result = new char[10];
    Arrays.fill(result, '0');
    String nonDigits = matcher.group(1);
    String digits = matcher.group(2);
    nonDigits.getChars(0, nonDigits.length(), result, 0);
    digits.getChars(0, digits.length(), result, 10 - digits.length());
    return String.valueOf(result);
}

Upvotes: 1

mike
mike

Reputation: 565

public static void main(String[] args) {
    System.out.println(padZero("abc123"));
}

public static String padZero(String init) {
    Matcher matcher = Pattern.compile("\\d+").matcher(init);
    matcher.find();
    return String.format("%s%0" + (10-matcher.start()) + "d", init.substring(0, matcher.start()), Integer.valueOf(matcher.group()));
}

Upvotes: 2

Related Questions