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

将字符串末尾n个字符移至另一字符串的最优高效实现方式

高效提取字符串末尾字符并删除的最优实现

需求与原实现

需求:从字符串str中取出最后times个字符存入removed,同时从str中删除这些字符。

原实现代码:

int times = std::stoi(arg); // arg is const std::string &        
std::string removed;
removed.resize(times); 
while (times > 0)
{
    removed[times-1] = str.back();
    str.pop_back();
    --times;
}

提问:在避免过度拷贝、多次遍历等情况下,完成该操作的最高效且优雅的方式是什么?


最优实现方案

直接借助C++ string的范围构造与截断能力,仅需一次内存分配、一次拷贝操作,完全规避循环遍历:

#include <algorithm> // 用于std::min
#include <string>

int times = std::stoi(arg);
// 先处理边界:防止times超过字符串实际长度导致越界
times = std::min(times, static_cast<int>(str.size()));

std::string removed(str.end() - times, str.end());
str.resize(str.size() - times);

方案优势

  • 极致效率:范围构造函数直接一次性拷贝目标字符,仅做一次内存分配,比逐个赋值/弹出的循环操作少了大量函数调用与循环开销
  • 代码简洁:两行核心代码完成需求,逻辑清晰易懂,无需手动处理字符顺序
  • 安全可靠:通过std::min处理times大于字符串长度的边界场景,避免迭代器越界风险

如果使用C++17及以上标准,也可以先用std::string_view临时获取末尾子串,但最终要存入std::string类型的removed时,上面的实现仍是最直接高效的选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:40:37