且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从任何字符串中获取最后三个字符-Java

更新时间:2023-02-04 22:48:28

为什么不只是 String substr = word.substring(word.length()-3)?

更新

在调用 substring()之前,请确保您检查 String 的长度至少为3个字符:

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has less than 3 characters!");
}