vsbsbsb

如果 @@ 的数量超过 {},可以在代码中添加逻辑处理多余的 @@。对于这种情况,我们假设逻辑如下:

  1. 如果 @@ 的值多于 {},多余的 @@ 将被忽略。
  2. 如果 @@ 的值少于 {},未匹配的 {} 用空字符串替换。

以下是增强后的代码:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::string replacePlaceholders(const std::string& input) {
    // 分离 @@ 前后的内容
    size_t separatorPos = input.find("@@");
    if (separatorPos == std::string::npos) {
        return input; // 如果没有 @@ 分隔符,直接返回原字符串
    }

    std::string placeholdersPart = input.substr(0, separatorPos); // {0}{1}{2}
    std::string valuesPart = input.substr(separatorPos + 2);      // Missing die cause Stop!@@->@@-->Arm: 0

    // 提取 @@ 后的值
    std::vector<std::string> values;
    size_t start = 0, end = 0;
    while ((end = valuesPart.find("@@", start)) != std::string::npos) {
        values.push_back(valuesPart.substr(start, end - start));
        start = end + 2;
    }
    if (start < valuesPart.size()) {
        values.push_back(valuesPart.substr(start));
    }

    // 替换 {} 占位符
    std::string result;
    for (size_t i = 0; i < placeholdersPart.size(); ++i) {
        if (placeholdersPart[i] == '{') {
            size_t closeBrace = placeholdersPart.find('}', i);
            if (closeBrace != std::string::npos) {
                try {
                    int index = std::stoi(placeholdersPart.substr(i + 1, closeBrace - i - 1));
                    if (index >= 0 && index < values.size()) {
                        result += values[index];
                    } else {
                        result += ""; // 索引超出范围,用空字符串替代
                    }
                } catch (...) {
                    result += ""; // 异常时用空字符串替代
                }
                i = closeBrace;
            } else {
                result += ""; // 缺少关闭括号时,用空字符串替代
            }
        } else {
            result += placeholdersPart[i];
        }
    }

    return result;
}

int main() {
    std::string input1 = "{0}{1}{2}@@A@@B@@C@@Extra@@Ignored";
    std::string input2 = "{0}{1}{2}{3}@@X@@Y";
    std::string input3 = "{0}{1}{2}@@A@@B@@C@@D";

    std::cout << replacePlaceholders(input1) << std::endl; // 输出:ABC
    std::cout << replacePlaceholders(input2) << std::endl; // 输出:XY
    std::cout << replacePlaceholders(input3) << std::endl; // 输出:ABC
    return 0;
}

关键逻辑:

  1. 多余的 @@ 处理:
    如果 values 中的元素超过 {} 占位符的数量,则多余的部分被忽略。

  2. 不足的 @@ 处理:
    如果 {} 占位符超过 values 的数量,则多余的 {} 替换为空字符串。

  3. 安全处理:
    继续保留之前的保护措施,例如索引超出范围、异常捕获等。

测试结果:

输入:

"{0}{1}{2}@@A@@B@@C@@Extra@@Ignored"
"{0}{1}{2}{3}@@X@@Y"
"{0}{1}{2}@@A@@B@@C@@D"

输出:

ABC
XY
ABC
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值