使用C++ Boost将字符串拆分为两部分?

And*_*ers 2 c++ string boost split

我希望能够将一个字符串分成两部分,leftright在第一次出现时separator.例如,使用#as作为分隔符left#right#more将导致leftright#more.

我有一个方法来做到这一点:

void misc::split(const string &input, string &left, string &right, char separator)
{
    int index = input.find(separator);
    if (index == string::npos)
    {
        left = input;
        right.erase();
    }
    else
    {
        right = input.substr(index + 1);
        left = input.substr(0, index);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我已经开始使用Boost了,并希望将这个相当冗长的代码压缩成更优雅的东西.我知道boost::split(),但在初始示例(和)中left,我给出了三个部分.rightmore

有什么建议?

seh*_*ehe 5

我预测它不会明显更好,因为如果内在的复杂性.

不过,这里有一个基于精神的样本:

static void split(const std::string &input, std::string &left, std::string &right, char separator)
{
    using namespace boost::spirit::qi;

    parse(input.begin(), input.end(), *~char_(separator) >> separator >> *char_, left, right);
}
Run Code Online (Sandbox Code Playgroud)

完整测试:

Live On Coliru

#include <boost/spirit/include/qi.hpp>

struct misc {
    static void split(const std::string &input, std::string &left, std::string &right, char separator)
    {
        using namespace boost::spirit::qi;

        parse(input.begin(), input.end(), *~char_(separator) >> separator >> *char_, left, right);
    }
};

int main() {
    for (std::string s : {
            "",
            "a",
            "a;",
            "a;b",
            ";b",
            ";",
            "a;b;",
            ";;" })
    {
        std::string l,r;
        misc::split(s,l,r,';');
        std::cout << "'" << s << "'\t-> l:'" << l << "'\tr:'" << r << "'\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

打印:

''  -> l:'' r:''
'a' -> l:'a'    r:''
'a;'    -> l:'a'    r:''
'a;b'   -> l:'a'    r:'b'
';b'    -> l:'' r:'b'
';' -> l:'' r:''
'a;b;'  -> l:'a'    r:'b;'
';;'    -> l:'' r:';'
Run Code Online (Sandbox Code Playgroud)