0

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;
    }
  }
Sha
  • 921
  • 17
  • 46

3 Answers3

3

One liner - return last character:

return Integer.parseInt(str.substring(str.length() - 1))); 

If you want to return 0 also when ends with 8 or 9 you will need to add a bit logic to it

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
2

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 :-).

Thihara
  • 7,031
  • 2
  • 29
  • 56
0

Extension from @user7294900 but multi-liner. In case you do not want to use regex.

    private int getEndNumber(final String str) {
        Integer num = 0;
        try {
            num =  Integer.parseInt(str.substring(str.length() - 1)) ; 
            num = num >= 7 ? 0 : num;
        } catch (NumberFormatException ex) {
            num = 0;
        }
        return num;
    }
Prashant Zombade
  • 482
  • 3
  • 15