【问题标题】:Boost split string by Blank Line通过空白行提升拆分字符串
【发布时间】:2020-10-10 22:50:27
【问题描述】:

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

这是我的意思的一个sn-p。

std::stringstream 源;
source.str(input_string);
std::string 行;
std::getline(source, line, '\0');
std::vector<:string> 标记;
boost:split(token,line, boost::is_any_of("这里的空行是什么");

【问题讨论】:

    标签: c++ string boost split


    【解决方案1】:

    您可以用双 \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"
    

    【讨论】:

    • 好的,我最初遇到了一个错误,所以让我澄清一下。我的 input_string 是一个字符串变量,所以它会修改 source.str(R"string") 中的 R 参数吗?我一直在尝试以多种不同的方式实现“\n\n”,但这看起来很有希望......
    • 您从字符串流开始。但正如您所见,line 已经是一个字符串。如果需要,请删除流:coliru.stacked-crooked.com/a/9f092da3fab87748
    • 为了好玩,不使用 Boost Regex(无链接)并在不分配大量令牌的情况下处理大文件:coliru.stacked-crooked.com/a/3e1e0682d44b42b7
    • 是的。这是不准确的。 Boost Regex 在许多方面要好得多,但是在“它是标准库的一部分”这一方面很难被击败。而所呈现的界面非常相似。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    相关资源
    最近更新 更多