java - 如何使用 endWith 函数有效且清晰地从字符串中获取数字?

标签 java string ends-with

我有诸如“Test1”、“Test2”之类的输入...并且我只是尝试在这些字符串中查找结束编号。我写了下面的代码,但我不喜欢它。我该如何改进这段代码?有什么建议吗?

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

最佳答案

单行 - 返回最后一个字符:

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

如果您想在以 89 结尾时也返回 0,则需要向其添加位逻辑

关于java - 如何使用 endWith 函数有效且清晰地从字符串中获取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183112/

相关文章:

java.lang.NoSuchMethodError : org. apache.commons.exec.PumpStreamHandler.setStopTimeout(J)V

Java 7 - LinkOption - 为什么 NOFOLLOW_LINKS 是唯一可用的选项?

c - 如何在 C 中实现可变长度 ‘string’ -y

Java:检查字符串是否包含多个字符

java - 我想要获得一周的值(value)

java - 如何发现 HashMap 中哪个值出现次数最多?

c - 在给定数组中查找最长的字符串后缀

如果路径以 "\"结尾,则 Powershell 命令修剪路径

python - 打印行的最短代码以 ['a' , 'b' ] 和以 ['y' , 'z' ] 结束 Python 3

java - 无法在 clojure 中加载 http-kit 库