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

2022-08-31 13:24:54

我正在尝试获取任何字符串的最后三个通道,并将其另存为另一个 String 变量。我的思维过程遇到了一些困难。

String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);

当涉及到缓冲区或索引时,我不知道如何使用getChars方法。Eclipse让我有这些。有什么建议吗?


答案 1

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

更新

请确保在呼叫之前检查是否至少为 3 个字符:Stringsubstring()

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 fewer than 3 characters!");
}

答案 2

我会考虑来自Apache Commons Lang的class方法:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)rightStringUtils

它是安全的。您将不会得到 或 .NullPointerExceptionStringIndexOutOfBoundsException

用法示例:

StringUtils.right("abcdef", 3)

您可以在上面的链接下找到更多示例。


推荐