在C++中如何将含空格、等号、引号的字符串解析到vector容器中
C++ 字符串拆分功能实现方案
拆分规则(基于需求总结)
- 空格为通用分隔符,双引号包裹的内容内部的空格不触发拆分
- 等号作为独立元素拆分,双引号内部的等号不单独拆分
- 双引号仅作为内容边界标记,不会存入结果列表
实现逻辑
- 用
in_quote布尔变量标记当前是否处于双引号包裹区间 - 用
temp临时字符串存储当前正在拼接的片段 - 逐字符遍历输入字符串,按字符类型分支处理
- 遍历结束后处理剩余未存入结果的片段
完整代码
#include <iostream> #include <vector> #include <string> using namespace std; void ParseFunc(string str, vector<string>& output) { bool in_quote = false; string temp; for (char c : str) { // 处理双引号边界 if (c == '"') { if (in_quote) { // 引号结束,存入引号内的内容 if (!temp.empty()) { output.push_back(temp); temp.clear(); } in_quote = false; } else { // 引号开始,先存入引号前的内容 if (!temp.empty()) { output.push_back(temp); temp.clear(); } in_quote = true; } continue; } // 处理非引号内的等号,单独作为元素 if (c == '=' && !in_quote) { if (!temp.empty()) { output.push_back(temp); temp.clear(); } output.push_back("="); continue; } // 处理非引号内的空格,作为分隔符 if (c == ' ' && !in_quote) { if (!temp.empty()) { output.push_back(temp); temp.clear(); } continue; } // 普通字符直接加入临时串 temp += c; } // 处理遍历结束后剩余的内容 if (!temp.empty()) { output.push_back(temp); } } int main() { // 如果不需要末尾的end,可直接删掉输入字符串最后的end string command = "hello world=\"i love coding\" abc=123 end"; vector<string> str; ParseFunc(command, str); for(int i = 0; i != str.size(); i++) { cout << str[i] << endl; } return 0; }
运行说明
如果将测试输入字符串末尾的end删除,运行结果将完全匹配你给出的期望输出。如果保留end,会在输出末尾额外多一行end。
内容的提问来源于stack exchange,提问作者Atomic
相关产品推荐
相关产品推荐

