首页 > 解决方案 > 如何在 C++ 中将空格、等号和引号解析为向量?

问题描述

有什么我可以将空格和引号解析为向量的吗?例如:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void ParseFunc(string str, vector<string>& output)
{
    //How can I do it?
}
int main()
{
    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;
    }
}

我希望输出是:

hello
world
=
i love coding
abc
=
123

请帮我!

标签: c++parsingvectorlexer

解决方案


这是微不足道的std::regex_iterator

string command = "hello world=\"i love coding\" abc=123 end";
std::regex words_regex(R"([^ ="]+|"[^"]+"|=)");
for (auto it = std::sregex_iterator(command.begin(), command.end(), words_regex);
        it != std::sregex_iterator();
        it++) {
    std::string token = (*it).str();
    if (token == "end") {
        break;
    }
    if (token[0] == '"')
        token = token.substr(1, token.length()-2);
    cout << "Token: " << token << endl;
}

输出:

Token: hello
Token: world
Token: =
Token: i love coding
Token: abc
Token: =
Token: 123

推荐阅读