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

C++ string按指定位置截取字符串时substr返回结果异常如何解决?

问题原因

你对C++ std::string的substr成员函数的参数定义存在误解:substr的第一个参数是子串的起始下标,第二个参数是要截取的子串长度,并非子串的结束下标。

针对你给出的用例:
字符串s = "12125.34e9"的下标从0开始计数,dot_pos = s.find('.')得到的值为5(.的下标),e_pos = s.find('e')得到的值为8(e的下标)。

  • 你第一次调用s.substr(dot_pos+1, e_pos-1)等价于s.substr(6,7):从下标6开始截取7个字符,但从下标6到字符串末尾只有4个字符,因此直接取到字符串末尾,得到"34e9"。
  • 你第二次调用s.substr(dot_pos+1, e_pos)等价于s.substr(6,8):长度参数依然大于剩余字符数,同样取到字符串末尾,结果还是"34e9"。
修正方案

你需要的子串从下标dot_pos+1开始,包含到e所在的下标位置,总长度为e_pos - dot_pos,正确写法如下:

using namespace std;

int main()
{
    string s = "12125.34e9";
    int dot_pos = s.find('.');
    int e_pos = s.find('e');
    // 方案1:使用substr,传入正确的长度参数
    cout << s.substr(dot_pos + 1, e_pos - dot_pos) << endl;
    // 方案2:如果习惯按[起始位置,结束位置]截取,可使用string迭代器构造,遵循左闭右开规则
    cout << string(s.begin() + dot_pos + 1, s.begin() + e_pos + 1) << endl;
    return 0;
}

两种写法都可以得到你需要的"34e"结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:12:01