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

C++ 如何将字符串中连续的1子串替换为其总数量

解决方案

方案1:手动遍历实现(推荐,性能更高、无正则依赖)

直接遍历字符串统计连续1的数量,遇到非1字符时先拼接统计到的1的数量,再拼接非1字符即可,逻辑简单且适配所有边界场景:

#include <string>
#include <iostream>

std::string replace_consecutive_ones(const std::string& input) {
    std::string result;
    int one_count = 0;
    for (char c : input) {
        if (c == '1') {
            one_count++;
        } else {
            if (one_count > 0) {
                result += std::to_string(one_count);
                one_count = 0;
            }
            result += c;
        }
    }
    // 处理字符串末尾为连续1的场景
    if (one_count > 0) {
        result += std::to_string(one_count);
    }
    return result;
}

int main() {
    std::string newDes = "1111P1P";
    std::cout << replace_consecutive_ones(newDes) << std::endl;
    // 输出结果:4P1P
    return 0;
}

方案2:正则匹配实现

如果希望用正则实现,不要用拆分逻辑,改为直接匹配连续1的片段,拼接时保留非匹配段即可:

#include <string>
#include <regex>
#include <iostream>

std::string replace_consecutive_ones_regex(const std::string& input) {
    std::regex re("1+");
    std::sregex_iterator it(input.begin(), input.end(), re);
    std::sregex_iterator end;
    std::string result;
    size_t last_pos = 0;
    
    for (; it != end; ++it) {
        // 拼接当前匹配段之前的非1字符
        result += input.substr(last_pos, it->position() - last_pos);
        // 拼接连续1的长度
        result += std::to_string(it->length());
        last_pos = it->position() + it->length();
    }
    // 拼接最后一段非1字符
    result += input.substr(last_pos);
    return result;
}

int main() {
    std::string newDes = "1111P1P";
    std::cout << replace_consecutive_ones_regex(newDes) << std::endl;
    // 输出结果:4P1P
    return 0;
}

原有代码问题说明

你最初的写法用非数字作为分隔符拆分字符串,只会提取出所有数字段,会直接丢弃作为分隔符的非数字字符,因此无法还原原字符串的完整结构,不适合该场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:54:03