我正在尝试获取任何字符串的最后三个字符并将其另存为另一个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)
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)
这很安全.你不会得到NullPointerException或StringIndexOutOfBoundsException.
用法示例:
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)
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
183918 次 |
| 最近记录: |