有没有快速的方法来获取字符串中的最后两个字符?

时间:2022-07-13 17:06:24

Wondering how to substring the last two characters quickly in Java?

想知道如何在Java中快速子字符串最后两个字符?

4 个解决方案

#1


98  

The existing answers will fail if the string is empty or only has one character. Options:

如果字符串为空或只有一个字符,则现有答案将失败。选项:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

要么

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

这是假设str是非空的,如果少于2个字符,你只需要原始字符串。

#2


14  

theString.substring(theString.length() - 2)

#3


12  

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

#4


4  

Use substring method like this::

使用这样的子串方法::

str.substring(str.length()-2);

#1


98  

The existing answers will fail if the string is empty or only has one character. Options:

如果字符串为空或只有一个字符,则现有答案将失败。选项:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

要么

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

这是假设str是非空的,如果少于2个字符,你只需要原始字符串。

#2


14  

theString.substring(theString.length() - 2)

#3


12  

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

#4


4  

Use substring method like this::

使用这样的子串方法::

str.substring(str.length()-2);