gpt4 book ai didi

c++ - 将 escaped_list_separator 与 boost split 结合使用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:07 27 4
gpt4 key购买 nike

我正在使用 boost 字符串库,并且刚刚发现 split 方法非常简单。

  string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
// If we didn't care about delimiter characters within a quoted section we could us
vector<string> tokens;
boost::split(tokens, str, boost::is_any_of(delimiters));
// gives the wrong result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters", " inside a quote\""}

这会很好而且简洁......但是它似乎不适用于引号,而是我必须做类似下面的事情

string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
vector<string> tokens;
escaped_list_separator<char> separator("\\",delimiters, "\"");
typedef tokenizer<escaped_list_separator<char> > Tokeniser;
Tokeniser t(str, separator);
for (Tokeniser::iterator it = t.begin(); it != t.end(); ++it)
tokens.push_back(*it);
// gives the correct result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters, inside a quote\""}

我的问题是,当您使用引号分隔符时,是否可以使用 split 或其他标准算法?感谢 purpledog,但我已经有了一种未被弃用的方法来实现预期的结果,我只是认为它非常麻烦,除非我可以用更简单、更优雅的解决方案替换它,否则我一般不会在不先将它包装起来的情况下使用它另一种方法。

编辑:更新代码以显示结果并澄清问题。

最佳答案

似乎没有任何简单的方法可以使用 boost::split 方法来做到这一点。我能找到的最短的代码是

vector<string> tokens; 
tokenizer<escaped_list_separator<char> > t(str, escaped_list_separator<char>("\\", ",", "\""));
BOOST_FOREACH(string s, escTokeniser)
tokens.push_back(s);

只比原始片段稍微冗长

vector<string> tokens;  
boost::split(tokens, str, boost::is_any_of(","));

关于c++ - 将 escaped_list_separator 与 boost split 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/890895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com