I am trying to make a program that given a string such as "hi99" it'd return "hi100", so basically adding 1 to the numbers in the last spots.
public static String incrementString(String str) {
String nonNumber = "";
String number = "";
int numberInt = 0;
for(int i = str.length() - 1 ; i >= 0 && Character.isDigit(str.charAt(i)); i--){
nonNumber = str.substring(0, i);
number = str.substring(i);
}
numberInt = Integer.valueOf(number) + 1;
number = Integer.toString(numberInt);
return (nonNumber + number);
}
My idea was to split the part with numbers from the part with no numbers. And then add one to the numbered part. Which is what i do below. Problem comes with the fact that, when Java sees 001, instead of adding 1 to the last spot and ignoring the rest. The ending value is 2. Therefore, I'm just asking to see if there's a way to avoid the removal of those zeroes.