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

如何仅反转字符串中的数字段 现有Java实现运行结果异常求排查

Java代码问题排查:反转字符串中连续数字段

原代码存在的3个核心问题

  • ans变量未正确赋值,连续数字段起始位置记录错误:你仅在ans==0时给firstindex赋值,但全程没有修改ans为非0值,导致每遍历到一个数字都会覆盖firstindex为当前下标,完全无法记录连续数字段的真实起始位置。
  • 末尾连续数字段不会被处理:反转逻辑仅写在「遇到非数字」的分支中,若字符串结尾为数字,遍历结束后不会触发反转,这部分数字保持原顺序不变。
  • 变量语义不清晰:ans变量无实际作用,完全可以移除。

错误输出原因说明

你给出的测试输入123ABC564在原代码执行时:遍历到前三个数字1、2、3时,firstindex会被依次覆盖为0、1、2,走到非数字字符A时,计算得到的反转区间是下标2到4(对应字符3、A、B),反转后这三个字符变为B、A、3,原123ABC段就变成12BAC3;末尾的564因为遍历结束后没有触发反转逻辑,保持原顺序,最终输出就和你得到的12BA3C564一致。

修正后可运行代码

public static void main(String []args){
    String str = "123ABC564";
    int count = 0;
    // 初始值设为-1,标记当前是否处于连续数字段中
    int firstIndex = -1;
    char[] ch = str.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        if (Character.isDigit(ch[i])) {
            if (firstIndex == -1) {
                // 首次遇到当前连续数字段的首个字符,记录起始下标
                firstIndex = i;
            }
            count++;
        } else {
            if (firstIndex != -1) {
                // 遇到非数字,前面有未反转的数字段,执行反转
                int lastIndex = count + firstIndex - 1;
                while (firstIndex < lastIndex) {
                    char temp = ch[firstIndex];
                    ch[firstIndex] = ch[lastIndex];
                    ch[lastIndex] = temp;
                    firstIndex++;
                    lastIndex--;
                }
                // 重置状态
                count = 0;
                firstIndex = -1;
            }
        }
    }
    // 遍历结束后,处理末尾可能存在的连续数字段
    if (firstIndex != -1) {
        int lastIndex = count + firstIndex - 1;
        while (firstIndex < lastIndex) {
            char temp = ch[firstIndex];
            ch[firstIndex] = ch[lastIndex];
            ch[lastIndex] = temp;
            firstIndex++;
            lastIndex--;
        }
    }
    // 输出结果
    for (char c : ch) {
        System.out.print(c);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:45:04