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

EGH*_*HDK 55 java

我正在尝试获取任何字符串的最后三个字符并将其另存为另一个String变量.我在思考过程中遇到了一些艰难的时期.

String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
Run Code Online (Sandbox Code Playgroud)

我不知道如何在缓冲区或索引时使用getChars方法.Eclipse让我有那些人.有什么建议?

Ego*_*gor 155

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

更新

请确保String在致电前检查至少3个字符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!");
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`Math.max()`就像这样`String substr = word.substring(Math.max(0,word.length() - 3)),可以很容易地避免使用负索引. (11认同)

Mic*_*cha 19

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

这很安全.你不会得到NullPointerExceptionStringIndexOutOfBoundsException.

用法示例:

StringUtils.right("abcdef", 3)

您可以在上面的链接中找到更多示例.


Boh*_*ian 15

这里有一些使用正则表达式完成工作的简洁代码:

String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
Run Code Online (Sandbox Code Playgroud)

此代码最多返回3; 如果少于3,则只返回字符串.

这是如何在没有正则表达式的情况下安全地完成它:

String last3 = str == null || str.length() < 3 ? 
    str : str.substring(str.length() - 3);
Run Code Online (Sandbox Code Playgroud)

通过"安全",我的意思是如果字符串为空或短于3个字符(所有其他答案都不是"安全"),则不会抛出异常.


上面的代码与此代码的效果完全相同,如果您更喜欢更详细,但可能更容易阅读的形式:

String last3;
if (str == null || str.length() < 3) {
    last3 = str;
} else {
    last3 = str.substring(str.length() - 3);
}
Run Code Online (Sandbox Code Playgroud)

  • @MvG所以这个答案"没用"?(这就是-1投票的意思).为什么使用三元语法没有用?你会把括号放在哪里?相反,我认为这个答案是有帮助的,特别是考虑到所有其他人如果提出空或短输入就会爆炸. (4认同)

Cra*_*lus 7

String newString = originalString.substring(originalString.length()-3);


Chr*_*ris 5

public String getLastThree(String myString) {
    if(myString.length() > 3)
        return myString.substring(myString.length()-3);
    else
        return myString;
}
Run Code Online (Sandbox Code Playgroud)