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

使用C++ getline()拆分字符串时如何忽略双引号内的逗号分隔符

解决方案

核心思路

std::getline 本身没有识别引号范围的内置逻辑,无法直接满足需求,需要自己补充状态判断实现:

  • 新增布尔类型的状态位,记录当前是否处于双引号包裹区间
  • 逐字符读取输入流内容,仅在非引号区间读到逗号时执行字段拆分

实现代码

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

int main() {
    std::istringstream args("[\"2,3\", 3]");
    std::string current_arg;
    std::vector<std::string> out_args;
    bool in_quote = false;
    char c;

    while (args.get(c)) {
        if (c == '"') {
            // 如果不需要保留字段中的引号,可删除下一行
            current_arg += c;
            in_quote = !in_quote;
        } else if (c == ',' && !in_quote) {
            // 非引号内的逗号作为拆分点
            out_args.push_back(current_arg);
            current_arg.clear();
        } else {
            current_arg += c;
        }
    }
    // 存入最后一个未处理的字段
    if (!current_arg.empty()) {
        out_args.push_back(current_arg);
    }

    // 测试输出拆分结果
    for (const auto& arg : out_args) {
        std::cout << arg << std::endl;
    }
    return 0;
}

扩展说明

上述代码执行后拆分得到的两个字段为["2,3"和 3],如果需要去掉首尾的方括号、字段前后的空格、包裹用的双引号,在每次拆分字段后新增对应的字符串清洗逻辑即可;如果需要支持转义引号的场景,可以额外新增转义状态位做判断处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:18:00