-1

I have the following string:

String numbersOfIds = "00000";

how to increment the last index in the following sequence 000001, 000002, 000003, 000004.

  • 2
    Any reason why you're using a `String` and not an `int`/`long`? You could have a counter variable and then convert that to a `String`, but that seems a bit redundant unless you have a reason for it to be a `String` – GBlodgett Nov 26 '18 at 22:44
  • 2
    If it quacks like an `Integer` and if it walks like an `Integer` then convert it into an `Integer` – ritratt Nov 26 '18 at 22:44
  • There no specific reason for using string as long as the numbers starts adds from the right to the left such as 000001 – Majda Elferjani Nov 26 '18 at 22:48
  • See https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left – isaace Nov 26 '18 at 22:50
  • 1
    Possible duplicate of [How can I pad an integer with zeros on the left?](https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left) – GBlodgett Nov 26 '18 at 22:51
  • Strings are immutable. You cannot change the contents of a String. All you can do is to generate a new String. It sounds like you have a formatting problem which you might solve by doing something like this:`System.out.printf("%06d: ", i);` , where i is your integer to be printed. – Tom Drake Nov 26 '18 at 22:56

1 Answers1

0

If the last character is less than '9' then increment it and stop, otherwise set it to '0', move one position to the left, and repeat instructions.

Like this:

public static String increment(String input) {
    char[] buf = input.toCharArray();
    for (int i = buf.length - 1; i >= 0; i--) {
        if (buf[i] >= '0' && buf[i] <= '8') {
            buf[i]++;
            return new String(buf);
        } else if (buf[i] != '9') {
            throw new IllegalArgumentException(input);
        }
        buf[i] = '0';
    }
    // Overflow, increase buffer size and prefix value with '1'
    char[] buf2 = new char[buf.length + 1];
    buf2[0] = '1';
    System.arraycopy(buf, 0, buf2, 1, buf.length);
    return new String(buf2);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247