c++ - 如何在 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
请帮我!
解决方案
这是微不足道的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
推荐阅读
- javascript - ChartJS: Position labels at end of doughnut segment
- node.js - Linking Service Hops with Zipkin and NodeJS
- regex - How can I find all instances of a group in regexp?
- latex - Formatting issues using RevTex 4.2
- kubernetes - Kubernetes: Update pod liveness probe timeoutSeconds
- python - Matlab mle fitting vs Python Scipy
- javascript - jquery focus function not working on checkbox
- google-chrome - UiPath cannot click Chrome Browser popup dialogs
- javascript - How to make Vue import files from assets folder instead of hardcoded script tags inside of index.html
- android - My app is not able to auto read OTP only for Redmi note 5 pro phones