Coding Challenge: Java Fundamentals
Updated:
✒ Reference: String incrementer
Challenge Description
Your job is to write a function which increments a string, to create a new string.
- If the string already ends with a number, the number should be incremented by 1.
- If the string does not end with a number. the number 1 should be appended to the new string.
Initial approach
I made a mistake by only checking the last character of the string to see if it is a number.
public static String incrementString(String str) {
int len = str.length() - 1;
char lastChar = str.charAt(len);
if (Character.isDigit(lastChar)) {
int nextInt = Character.getNumericValue(lastChar) + 1;
return (str.substring(0, len)).concat(Integer.toString(nextInt));
} else {
return str + "1";
}
}
But this only increments the last character, and becomes a problem if the number is more than two digits long and ends with 9. (i.e. foo119
becomes foo1110
)
Next approach
So I checked for the leading 0s, then padded the string with the appropriate number of 0s.
public class Kata {
public static String incrementString(String str) {
for (int i=0; i<str.length(); i++) {
// Check if character contains digit
if (Character.isDigit(str.charAt(i))) {
// Create a number 1 bigger
String strInt = str.substring(i, str.length());
int nextInt = Integer.valueOf(str.substring(i, str.length())) + 1;
// If there is a leading zero, add it to string
if (Integer.toString(nextInt).length() < strInt.length()) {
String result = String.format("%0" + strInt.length() + "d", nextInt);
return (str.substring(0, i)).concat(result);
}
// If not, just return without leading 0s
return (str.substring(0, i).concat(Integer.toString(nextInt)));
}
}
return str + "1";
}
}
But this does not take into account the strings with numbers in the middle, for example 99obar99
.
I should consider using Regex to check for trailing numbers!
Leave a comment