I have inputs like "Test1","Test2"... and I just try to find end number in these strings. I wrote below code but I don't like it. How can I improve this code? Is there any advice?
private int getEndNumber(final String str) {
if (str.endsWith("1")) {
return 1;
} else if (str.endsWith("2")) {
return 2;
} else if (str.endsWith("3")) {
return 3;
} else if (str.endsWith("4")) {
return 4;
} else if (str.endsWith("5")) {
return 5;
} else if (str.endsWith("6")) {
return 6;
} else if (str.endsWith("7")) {
return 7;
} else {
return 0;
}
}
Regex is your friend.
Pattern p = Pattern.compile("[0-9]+$"); // This regex matches the last number
Matcher m = p.matcher(str); // Create the matcher
//If the pattern matches then we get the matching string
if(m.find()) {
result = m.group();
}
You can alternatively iterate the string in reverse and check if the characters are integers, but that's rather tedious than using regexes.
There's a nice article about regexes here http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
You read it thoroughly and forget everything in a few days, like the most of us :-).