C++/Boost split a string on more than one character
Asked Answered
U

3

8

This is probably really simple once I see an example, but how do I generalize boost::tokenizer or boost::split to deal with separators consisting of more than one character?

For example, with "__", neither of these standard splitting solutions seems to work :

boost::tokenizer<boost::escaped_list_separator<string> > 
        tk(myString, boost::escaped_list_separator<string>("", "____", "\""));
std::vector<string> result;
for (string tmpString : tk) {
    result.push_back(tmpString);
}

or

boost::split(result, myString, "___");
Upstretched answered 3/4, 2013 at 13:58 Comment(2)
Please be specific about what "does not seem to work" means.Dandiprat
possible duplicate of Boost::Split using whole string as delimiterMurray
C
12
boost::algorithm::split_regex( result, myString, regex( "___" ) ) ;
Cason answered 3/4, 2013 at 14:2 Comment(2)
Can you please let me know that are the header files to be included to do this?Undesigning
@Undesigning Try: #include <boost/algorithm/string_regex.hpp>Damar
F
2

Non-boost solution

vector<string> split(const string &s, const string &delim){
    vector<string> result;
    int start = 0;
    int end = 0;
    while(end!=string::npos){
        end = s.find(delim, start);
        result.push_back(s.substr(start, end-start));
        start = end + delim.length();
    }
    return result;
}
Fane answered 17/7, 2019 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.