我如何在 C++ 中将空格、相等和引号解析为向量?

How can i parse whitespace, equal and quotes to vector in C++?

有没有我可以解析 space 和引号的向量? 例如:

#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

请帮帮我!

这对于 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

更简单的是:

#include <iostream>
#include <string>
#include <regex>
#include <vector>
#include <algorithm>
#include <iterator>

const std::string com = "hello world=\"i love coding\" abc=123 end";
const std::regex re(R"(\"(.*?)\"|(\w+)|([=]))");

int main() {

    // Here we will store the results of the splitting
    std::vector<std::string> result{};

    // Split
    std::transform(std::sregex_token_iterator(com.begin(), com.end(), re), {}, std::back_inserter(result),
        [](std::string s) { return std::regex_replace(s, std::regex("\""), ""); });

    // Output
    std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

一个典型的 Lambda 方法语句...