一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java中 StringIndexOutOfBoundsException 字符串截取越界如何解决

时间:2026-07-16 08:11:54 编辑:袖梨 来源:一聚教程网

字符串截取越界异常源于访问不存在的索引,核心解决思路是截取前校验边界:确保0≤beginIndex≤endIndex≤string.length(),并防范null、空串、indexOf返回-1等常见错误,推荐使用Math.min/max或StringUtils等安全封装。

字符串截取越界(StringIndexOutOfBoundsException)本质是访问了字符串不存在的索引位置,核心解决思路是:**截取前校验边界,确保起始和结束索引合法**。

检查 substring 的起始和结束索引是否越界

String.substring(int beginIndex, int endIndex) 要求:
0 ≤ beginIndex ≤ endIndex ≤ string.length()
– 任意一个不满足就会抛出异常。

常见错误写法:

  • 直接用用户输入或计算结果当索引,没校验长度(如 str.substring(5, 10),但 str.length() 只有 3)
  • indexOf 查找分隔符后未判断是否为 -1,就直接用于截取
  • 对空字符串或 null 字符串调用 substring

✅ 正确做法:先判断再截取

if (str != null && str.length() >= 10) {    String sub = str.substring(5, 10);} else {    String sub = ""; // 或抛自定义异常、返回默认值}

安全获取子串的常用模式

把边界校验封装成可复用逻辑,避免重复出错:

立即学习“Java免费学习笔记(深入)”;

  • 按长度安全截取前 N 位str.substring(0, Math.min(n, str.length()))
  • 从某位置开始取最多 m 个字符str.substring(start, Math.min(start + m, str.length()))
  • 按分隔符分割并安全取段:先 int idx = str.indexOf("-");,再 if (idx != -1) { ...substring(0, idx)... }

使用 Optional 或工具类简化判空与截取

借助 Apache Commons Lang 的 StringUtils 可大幅降低出错概率:

  • StringUtils.substring(str, 5, 10):自动处理 null 和越界,返回 null 或截取结果
  • StringUtils.left(str, 5)StringUtils.right(str, 3):安全取左右子串
  • StringUtils.substringBefore(str, "-"):按分隔符安全截取前半部分

若不能引入第三方库,可自己封装一个轻量工具方法:

public static String safeSubstring(String s, int from, int to) {    if (s == null || from < 0 || from > to) return "";    int len = s.length();    int start = Math.max(0, Math.min(from, len));    int end = Math.max(start, Math.min(to, len));    return s.substring(start, end);}

调试时快速定位越界原因

遇到异常不要只看堆栈,重点查三件事:

  • 打印原始字符串内容和长度:System.out.println("str='" + str + "', len=" + str.length());
  • 打印你要用的索引值:System.out.println("begin=" + begin + ", end=" + end);
  • 确认这些索引是否由外部输入、正则匹配、JSON 解析等不可控来源产生——这些地方最易埋雷

不复杂但容易忽略。

热门栏目