stackerstack
stackerstack

Reputation: 265

Java how to increment a string of an integer with leading zeros?

Is there a shortcut or way to increment a string that is a number with leading zeros?

For example:

000
001
002
003
...
etc

Upvotes: 2

Views: 3219

Answers (3)

ray
ray

Reputation: 1690

You can do the following,

public class Main {
    public static void main(String[] args) {
        String s = "001";
        Integer i = Integer.parseInt(s);
        i++;
        s = String.format("%0" + s.length() + "d", i);
        System.out.println(s);
    }
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 425458

Parse the string as an long, increment it, then format it using the length of the input as the width of the output:

str = String.format("%0" + str.length() + "d", Long.parseLong(str) + 1);

This works for any width of input (up to 19 digits anyway).

Note: Overflowing the width of the input string will not stay within the width. eg "999" will produce "1000"

Upvotes: 3

user4910279
user4910279

Reputation:

Try this.

static final Pattern NUMBER = Pattern.compile("\\d+");

static String increment(String input) {
    return NUMBER.matcher(input)
        .replaceFirst(s -> String.format(
            "%0" + s.group().length() + "d",
            Integer.parseInt(s.group()) + 1));
}

public static void main(String args[]) {
    System.out.println(increment("001"));
    System.out.println(increment("012345"));
    System.out.println(increment("ABC0123"));
}

output:

002
012346
ABC0124

Upvotes: 1

Related Questions