java如何截取末尾符
截取字符串末尾字符的方法
在Java中,截取字符串末尾字符可以通过多种方式实现,具体取决于需求。以下是几种常见的方法:
使用 substring 方法
通过 substring 方法结合字符串长度可以截取末尾的字符。例如,截取最后一个字符:
String str = "Hello";
String lastChar = str.substring(str.length() - 1);
System.out.println(lastChar); // 输出 "o"
截取最后N个字符:
String lastNChars = str.substring(str.length() - 3); // 截取最后3个字符
System.out.println(lastNChars); // 输出 "llo"
使用 charAt 方法

如果只需要获取最后一个字符而不是子字符串,可以使用 charAt:
char lastChar = str.charAt(str.length() - 1);
System.out.println(lastChar); // 输出 'o'
处理空字符串
在实际应用中,需要检查字符串是否为空,避免抛出异常:

if (!str.isEmpty()) {
String lastChar = str.substring(str.length() - 1);
} else {
System.out.println("字符串为空");
}
使用正则表达式
如果需要截取特定模式的末尾字符,可以使用正则表达式:
String str = "Hello123";
String lastDigits = str.replaceAll(".*?(\\d+)$", "$1");
System.out.println(lastDigits); // 输出 "123"
使用 Apache Commons Lang 库
如果项目中引入了 Apache Commons Lang,可以使用 StringUtils 提供的方法:
import org.apache.commons.lang3.StringUtils;
String lastChar = StringUtils.substring(str, -1); // 截取最后一个字符
String lastNChars = StringUtils.substring(str, -3); // 截取最后3个字符
注意事项
- 字符串长度为0时,直接调用
substring或charAt会抛出StringIndexOutOfBoundsException,需提前检查。 - 如果字符串可能为
null,需先进行判空处理。 - 使用正则表达式时,确保模式与字符串的实际内容匹配。
以上方法可以根据具体需求选择,通常 substring 是最直接和高效的方式。






