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

如何使用C++ <algorithm>库实现字符串除最后指定位外全部掩码替换

实现方案

完全可以通过<algorithm>头文件的标准算法实现对应功能,以下是具体实现方案:

1. 使用std::transform实现

无需修改原字符串,直接生成掩码后的新字符串:

#include <algorithm>
#include <string>
#include <iostream>

int main() {
    std::string barcode = "300001629197835714";
    const size_t keep_last = 4; // 自定义保留的末尾字符位数
    std::string out;
    out.reserve(barcode.size()); // 预分配空间提升性能

    size_t idx = 0;
    std::transform(barcode.begin(), barcode.end(), std::back_inserter(out),
        [&](char c) {
            size_t mask_len = barcode.size() > keep_last ? barcode.size() - keep_last : 0;
            return idx++ < mask_len ? '*' : c;
        });
    
    std::cout << out << std::endl;
    return 0;
}

2. 使用std::replace_if实现

直接在原字符串的副本上修改,逻辑更直观:

#include <algorithm>
#include <string>
#include <iostream>

int main() {
    std::string barcode = "300001629197835714";
    const size_t keep_last = 4;
    std::string out = barcode;
    size_t idx = 0;

    std::replace_if(out.begin(), out.end(),
        [&](char) {
            size_t mask_len = out.size() > keep_last ? out.size() - keep_last : 0;
            return idx++ < mask_len;
        }, '*');
    
    std::cout << out << std::endl;
    return 0;
}

补充:更高性能的非算法实现

如果没有强制要求使用<algorithm>的算法函数,直接通过字符串构造和子串截取的方式代码更简洁、性能更高,同时兼容字符串长度小于保留位数的边界场景:

#include <string>
#include <iostream>

int main() {
    std::string barcode = "300001629197835714";
    const size_t keep_last = 4;
    size_t mask_len = barcode.size() > keep_last ? barcode.size() - keep_last : 0;
    std::string out(mask_len, '*');
    out += barcode.substr(mask_len);

    std::cout << out << std::endl;
    return 0;
}

内容的提问来源于stack exchange,提问作者the.cicada.himself

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:27:03