You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中截取指定长度字符串切片的异常问题排查

问题分析与解决方案

首先看你遇到的问题:首次截取的切片符合长度要求,但后续结果无效,大概率是循环的起始索引范围计算错误,以及可能对substring方法的参数逻辑理解有偏差。

先拆解你的代码问题点:

  • maxBeginSlice的计算公式listBits.length() - (width * 2) + 1完全不合理,这会让循环提前终止,甚至当width*2大于字符串长度时,这个值会变成负数,循环直接跳过后续迭代。
  • Java的substring(beginIndex, endIndex)方法中,endIndex是排他的——要截取长度为width的子串,正确写法是substring(x, x + width),且x + width不能超过字符串总长度,否则会抛出索引越界异常。

修正后的代码示例

假设你需要的是滑动窗口式的连续切片(每次移动1个字符,截取长度为6的子串),代码如下:

class Counter {
    public static void main(String[] args) {
        String listBits = "5,1,1,5,0,5,3,3,2,0,2,3,1,1,0,";
        int width = 6;
        
        // 计算最大起始索引:起始位置 + width 不能超过字符串长度
        int maxStartIndex = listBits.length() - width;
        
        System.out.println("原字符串:" + listBits);
        System.out.println("截取的" + width + "长度切片:");
        
        for (int x = 0; x <= maxStartIndex; x++) {
            String stringSlice = listBits.substring(x, x + width);
            System.out.println(stringSlice);
        }
    }
}

如果你的需求是不重叠的切片(每次截取6个字符后,直接跳过6个字符继续截取),只需要修改循环的步长:

for (int x = 0; x <= maxStartIndex; x += width) {
    String stringSlice = listBits.substring(x, x + width);
    System.out.println(stringSlice);
}

额外注意点

  • 如果width的值大于字符串总长度,要提前做判断避免异常:
    if (width > listBits.length()) {
        System.out.println("截取长度大于字符串总长度,无法执行截取");
        return;
    }
    
  • 如果你实际想截取的是6个完整元素(比如"5,1,1,5,0,5"这类包含6个数字的组合),那width应该设为12(每个元素是"数字+逗号",占2个字符),这样就能准确截取6个完整元素的子串。

内容的提问来源于stack exchange,提问作者Gilberto Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:21:47