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

报错:String index out of range: 4,求Java字符串处理代码的排查与修复

字符串索引越界问题排查与修复

问题原因

你的代码触发String index out of range错误,核心原因是循环边界条件错误:
Java字符串的索引从0开始,最大有效索引为字符串长度-1。但你在两个for循环中使用了i <= firstInput.length()和b <= secondInput.length()的判断条件,当循环变量等于字符串长度时,charAt()方法访问的是不存在的索引位置,直接抛出越界异常。

以你的测试用例为例:firstInput是"reba",长度为4,有效索引是0-3,当i=4时调用firstInput.charAt(4)就会触发错误。

修复后的代码

把循环条件中的<=改为<,确保循环变量只在有效索引范围内遍历:

package stringAnalyze;

public class CommonLetters {

    public static void main(String[] args) {
        getLetters("reba", "oeoe");
    }

    public static String getLetters(String firstInput, String secondInput) {
        String newLetters = "";
        // 修正循环条件为 < 字符串长度
        for (int i = 0; i < firstInput.length(); i++) {
            for (int b = 0; b < secondInput.length(); b++) {
                if (firstInput.charAt(i) == secondInput.charAt(b)) {
                    newLetters += secondInput.charAt(b);
                }
            }
        }
        return newLetters;
    }
}

额外优化建议(可选)

原代码会重复添加多次相同的共同字符(比如测试用例中会返回"ee"),如果需要去重,可改用StringBuilder结合Set实现:

import java.util.HashSet;
import java.util.Set;

package stringAnalyze;

public class CommonLetters {
    public static void main(String[] args) {
        System.out.println(getLetters("reba", "oeoe")); // 输出e
    }

    public static String getLetters(String firstInput, String secondInput) {
        Set<Character> commonChars = new HashSet<>();
        for (char c : firstInput.toCharArray()) {
            if (secondInput.indexOf(c) != -1) {
                commonChars.add(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (char c : commonChars) {
            sb.append(c);
        }
        return sb.toString();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:15:44