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;
    }
  }
4

3 回答 3

3

一个班轮 - 返回最后一个字符:

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

如果你想在结束时也返回 08或者9你需要向它添加一些逻辑

于 2019-01-14T14:16:56.310 回答
2

正则表达式是你的朋友。

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();
}

您也可以反向迭代字符串并检查字符是否为整数,但这比使用正则表达式更乏味。

这里有一篇关于正则表达式的好文章http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

像我们大多数人一样,您仔细阅读并在几天内忘记所有内容:-)。

于 2019-01-14T14:16:06.793 回答
0

从@user7294900 扩展,但多线。如果您不想使用正则表达式。

    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;
    }
于 2019-01-14T15:33:31.190 回答