6

使ってます

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." 

もちろん、トークンの最初と最後で引用符を検索し、 ""を使用してマージすると、引用符で始まるトークンと引用符で終わるトークンの間にトークンが区切られ、引用符で囲まれた文字列が再作成されますが、疑問に思っています。これを行うためのより効率的でエレガントな方法がある場合。何か案は?

4

2 に答える 2

15
于 2012-11-15T21:42:23.030 に答える
0

このソリューションが移植可能かどうかはわかりませんが(のconst条件に違反していますbool operator() (char ch) 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;
}

結果:

command_name
first_argument
"Second argument which is a quoted string."
additional_argument
于 2012-11-15T21:37:58.490 に答える