C++ 使用C+拆分字符串+;boost::在引用文本中不拆分而拆分

C++ 使用C+拆分字符串+;boost::在引用文本中不拆分而拆分,c++,boost,split,C++,Boost,Split,我正在使用 boost::split(strs, r_strCommandLine, boost::is_any_of("\t ")); 将字符串吐入令牌以解析简单脚本。到目前为止,一切顺利。但是,对于以下字符串 command_name first_argument "Second argument which is a quoted string." 我想要我的代币 strs[0] = command_name strs[1] = first_argument strs[2] = "S

我正在使用

boost::split(strs, r_strCommandLine, boost::is_any_of("\t "));
将字符串吐入令牌以解析简单脚本。到目前为止,一切顺利。但是,对于以下字符串

command_name first_argument "Second argument which is a quoted string." 
我想要我的代币

strs[0] = command_name
strs[1] = first_argument
strs[2] = "Second argument which is a quoted string." 

当然,我可以在标记的开头和结尾搜索引号字符,并使用“”分隔符将标记合并到以引号开头的标记和以引号结尾的标记之间,以重新创建带引号的字符串,但我想知道是否有更有效/优雅的方法来执行此操作。有什么想法吗?

我不确定这个解决方案是否是可移植的(我们违反了
bool operator()(char ch)const
的const条件),但它是有效的

这个解决方案在理论上很有趣,我不会在实际项目中使用它

#include <boost/algorithm/string/split.hpp>
#include <string>
#include <vector>
#include <iostream>

class split_q {
public:
    split_q() : in_q(false) {}
    bool operator() (char ch) const
    {
        if (ch == '\"') in_q = !in_q;
        return !in_q && ch == ' ';
    }

private:
    mutable bool in_q;

};

int main(int argc, char* argv[])
{
    std::string in = "command_name first_argument \"Second argument which is a quoted string.\" additional_argument";
    std::vector<std::string> res;
    boost::algorithm::split(res, in, split_q());

    for (size_t i = 0; i < res.size(); ++i)
        std::cout << res[i] << std::endl;

    return 0;
}
示例使用:

#包括
#包括
使用std::cout;
使用std::string;
#包括
使用boost::tokenizer;
使用boost::转义\u列表\u分隔符;
typedef标记器so_标记器;
int main()
{
字符串s(“命令名第一个参数”
“\”第二个参数是带引号的字符串。\”;
所以标记器tok(s,转义的列表分隔符('\\',''\');
for(so_标记器::迭代器beg=tok.begin();beg!=tok.end();++beg)
{

不欢迎使用堆栈溢出!我被你的问题弄糊涂了。这个问题的第一段是否与问题的其余部分有任何关系?可能有你需要的功能。拆分可能太简单了,因为你确实需要某种形式的解析。@Yakk是的。要拆分的字符串看起来像字符串(“命令\u name first\u argument\“第二个参数,它是一个带引号的字符串。\”“)@Robᵩ 不,这很奇怪。第一段是我昨天在另一篇帖子上发表的评论。如果我编辑当前的问题,我根本看不到第一段,所以我无法删除它…奇怪的行为。你可以通过将
bool*存储在_q
中,而不是在_q
中存储
mutable
,以及一个backsl>来修复
常量ash escape state应该很容易添加。我关心的不是使用mutable关键字,而是实际违反了不可变性如果在函子中存储指针,就不会违反不可变性。变异函子的最大问题是,您依赖于算法只使用函子的一个实例,而不是复制--如果发生这种情况,您会遇到问题。我看到的指针版本的唯一问题是算法可能会运行不正常。@Yakk谢谢,您详细描述了这种方法的问题有办法保留引号吗?我需要输出类似于:
命令名称
第一个参数
”第二个参数是带引号的字符串。“
command_name
first_argument
"Second argument which is a quoted string."
additional_argument
#include <string>
#include <iostream>
using std::cout;
using std::string;

#include <boost/tokenizer.hpp>
using boost::tokenizer;
using boost::escaped_list_separator;

typedef tokenizer<escaped_list_separator<char> > so_tokenizer;

int main()
{
    string s("command_name first_argument "
             "\"Second argument which is a quoted string.\"");

    so_tokenizer tok(s, escaped_list_separator<char>('\\', ' ', '\"'));
    for(so_tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg)
    {
        cout << *beg << "\n";
    }

    return 0;
}
command_name first_argument Second argument which is a quoted string.