I have the following string:
String numbersOfIds = "00000";
how to increment the last index in the following sequence 000001, 000002, 000003, 000004.
I have the following string:
String numbersOfIds = "00000";
how to increment the last index in the following sequence 000001, 000002, 000003, 000004.
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);
}