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

如何在C++中替换子字符串的最后一次出现

替换字符串中子串的最后一次出现

方法一:原生字符串操作(高效推荐)

针对固定子串的替换需求,用C++原生字符串操作比正则表达式更高效,无需引入regex库:

  • 用string::rfind()从字符串末尾向前查找目标子串的最后一次出现位置
  • 若找到位置,将原字符串拆分为「前半部分」+「替换串」+「后半部分」拼接
  • 未找到则直接返回原字符串

代码示例:

#include <iostream>
#include <string>

int main ()
{
    std::string s ("There {x:y} is a {x:y},u bench");
    const std::string target = "{x:y}";
    const std::string replacement = "{r:w}";
    
    size_t last_pos = s.rfind(target);
    if (last_pos != std::string::npos) {
        s = s.substr(0, last_pos) + replacement + s.substr(last_pos + target.length());
    }
    
    std::cout << s << std::endl;
    return 0;
}

注:这里匹配完整的{x:y}而非单独的x:y,避免误匹配其他包含x:y的片段。

方法二:正则表达式实现

如果必须用正则,可以构造匹配「最后一次出现子串」的表达式,利用负向预查确保后续无重复子串:

代码示例:

#include <iostream>
#include <regex>

int main ()
{
    std::string s ("There {x:y} is a {x:y},u bench");
    // 匹配最后一处x:y,(?!.*x:y)确保后续无x:y
    std::regex e(R"(x:y(?!.*x:y))"); 
    std::cout << std::regex_replace(s, e, "r:w") << std::endl;
    return 0;
}

这种方法适合复杂匹配场景,但性能不如原生字符串操作。

内容的提问来源于stack exchange,提问作者M.A.G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:33:25