What would be the most performant way to get the last 2 digits of a string?
For example: getLastTwoDigits("a1b2cd3e4ghi5jk")
must return "45"
;
I had already asked how to get the first two digits of a string. But now I need a performant way to get the last two digits.
I've adapted the answer I received in the other question and I could make it work using the code below. However, I know that I've defeated the purpose of StringBuilder when I used sb.insert(0, char)
.
private static String getLastTwoDigits(String s) {
if(s==null)
return null;
StringBuilder sb = new StringBuilder(2);
char charArray[] = s.toCharArray();
for (int i = charArray.length-1; i>=0; i--) {
if (Character.isDigit(charArray[i])) {
sb.insert(0, charArray[i]);
if (sb.length() == 2)
break;
}
}
return sb.toString();
}
I imagine that StringBuider is not the right tool for this case. So what would be the most performant solution?