c++ - 通过空行 boost 分割字符串

标签 c++ string boost split

有没有办法在遇到空行时使用 boost::split 来分割字符串?

这是我的意思的一个片段。

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");

最佳答案

您可以按双 \n\n 分割,除非您将空行表示为“可能包含其他空白的行”。

<强> 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";
    }
}

打印

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

在“空”行上允许有空格

用正则表达式表达即可:

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

现在输出是: Live On Coliru

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

关于c++ - 通过空行 boost 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62491337/

相关文章:

c++ - 什么可以防止异常被捕获?

c++ - 返回字符串的静态方法

java - 修改java现有正则表达式以允许一个新字符的最佳方法

c++ - Raspberry Pi 2 上的 g++-4.9:链接时对 `boost::atomics::detail::lockpool::get_lock_for 的 undefined reference

c++ - 错误 : no matching function for call to ‘min(long unsigned int&, unsigned int&)’

c++ boost写入内存映射文件

c++ - 如何将 date::year_month_day 转换为 chrono time_point

c++ - 我应该在插入 STL 集之前随机洗牌吗?

c++ - 字符串类中 c_str 函数的内存分配

string - Swift:CFArray:获取值作为 UTF 字符串