Search code examples
c++stringboostsplit

Boost split string by Blank Line


Is there a way to use boost::split to split a string when a blank line is encountered?

Here is a snippet of what I mean.

std::stringstream source;
source.str(input_string);
std::string line;
std::getline(source, line, '\0');
std::vector<std::string> token;
boost:split(token,line, boost::is_any_of("what goes here for blank line");

Solution

  • You can split by double \n\n unless you meant blank line as "a line that may contain other whitespace".

    Live On Coliru

    #include <boost/regex.hpp>
    #include <boost/algorithm/string_regex.hpp>
    #include <boost/algorithm/string/classification.hpp>
    #include <sstream>
    #include <iostream>
    #include <iomanip>
    
    int main() {
        std::stringstream source;
        source.str(R"(line one
    
    that was an empty line, now some whitespace:
          
    bye)");
    
        std::string line(std::istreambuf_iterator<char>(source), {});
        std::vector<std::string> tokens;
    
        auto re = boost::regex("\n\n");
        boost::split_regex(tokens, line, re);
    
        for (auto token : tokens) {
            std::cout << std::quoted(token) << "\n";
        }
    }
    

    Prints

    "line one"
    "that was an empty line, now some whitespace:
          
    bye"
    

    Allow whitespace on "empty" lines

    Just express it in a regular expression:

    auto re = boost::regex(R"(\n\s*\n)");
    

    Now the output is: Live On Coliru

    "line one"
    "that was an empty line, now some whitespace:"
    "bye"