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

为何我的C++字符串erase-remove惯用法实现带条件语句会引发无限循环?

字符串erase方法实现的问题修复

问题分析

你尝试实现字符串的erase功能,原代码存在索引越界问题,修改后又出现无限循环。当前delStr函数的核心问题如下:

  • 无限循环根源:循环条件while(n--)逻辑错误。n初始为s.length()-1,但该条件仅根据n的递减次数控制循环,完全忽略了i的实际进度。当i跳过一段字符后,循环仍会继续执行直到n变为负数,而此时i可能早已超出字符串长度,导致后续操作越界且循环无法正确终止。
  • 索引越界风险:当i += nChar后,i可能大于等于字符串长度,此时执行ans.push_back(s[i])会访问非法内存。
  • 缺少返回值:函数声明返回string,但代码末尾没有return ans;,会触发未定义行为。
  • 冗余判断无效:if(n<0) break;的位置错误,无法提前终止非法循环。

修复后的代码

正确的实现思路应该是遍历原字符串,根据索引判断是否跳过指定区间,直到遍历完所有有效字符:

string delStr(string s, int sIdx, int nChar) {
    string ans = "";
    int i = 0;
    int len = s.length();
    while (i < len) {
        // 到达起始删除位置,跳过指定数量的字符
        if (i == sIdx) {
            i += nChar;
            continue;
        }
        // 添加当前字符并移动索引
        ans.push_back(s[i]);
        i++;
    }
    return ans;
}

额外优化说明

增加参数合法性检查,避免非法输入导致的异常:

string delStr(string s, int sIdx, int nChar) {
    int len = s.length();
    // 处理非法参数:起始位置越界、删除数量为负,直接返回原字符串
    if (sIdx < 0 || sIdx >= len || nChar <= 0) {
        return s;
    }
    // 计算实际需要删除的字符数,避免超出字符串末尾
    int actualDel = min(nChar, len - sIdx);
    string ans = "";
    int i = 0;
    while (i < len) {
        if (i == sIdx) {
            i += actualDel;
            continue;
        }
        ans.push_back(s[i]);
        i++;
    }
    return ans;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:53:14