【问题标题】:How to split a string and keep the delimiters using boost::split?如何拆分字符串并使用 boost::split 保留分隔符?
【发布时间】:2014-03-18 08:49:59
【问题描述】:

我有一个这样的字符串:

std::string input("I #am going to# learn how #to use #boost# library#");

我这样做:

std::vector<std::string> splitVector;
boost::split(splitVector, input, boost::is_any_of("#"));

得到了这个:(splitVector)

splitVector:
        "I "
        "am going to"
        " learn how " 
        "to use "
        "boos"
        " library"
        "" // **That's odd, why do I have an empty string here ?**

但是需要这样的东西:

splitVector:
    "I "
    "#am going to"
    "# learn how "
    "#to use "
    "#boost"
    "# library"
    "#"

如何做到这一点?或者也许在 boost 库中还有另一种方法可以做到这一点? 为什么我在splitVector 中得到一个空字符串?

【问题讨论】:

  • 为什么需要保留分隔符?
  • @gg.kaspersky,好问题!结果我必须恢复相同的字符串(使用 splitVector 构建它),并且我有一个问题来检测字符串中有多少定界符,奇数或偶数,换句话说,我总是恢复它,因为它有偶数分隔符。例如:如果我有字符串“#test”和“#test#”并将其拆分,获取第一个字符串“test”和相同的第二个字符串“test”,并将两个字符串恢复为“#test#”跨度>
  • 有空字符串是因为最后一个分隔符后面的输入字符串是空的。由于您的分隔符是单个字符,您可以简单地将字符添加(或附加)到结果字符串。如果有许多不同的分隔符,我认为 boost split 没有您需要的功能。有关其他解决方案,请参阅例如 this question。
  • split on "#test#" 应该返回 {"","test",""}?
  • @edwin,我不确定我是否正确理解了您的 restore-string-use-case,但是 1. 您可以使用 join (stackoverflow.com/questions/1833447/…) 和 2. Number of ' 重建原始字符串#' 等于 splitVector.size() - 1

标签: c++ boost


【解决方案1】:

您不能使用boost::split,因为使用来自boost/algorithm/string/find_iterator.hppsplit_iterator 的内部实现会吞下令牌。

但是,您可以使用 boost::tokenizer,因为它可以选择保留分隔符:

只要在输入序列中看到分隔符,当前标记就结束了,新标记开始。 dropped_delims 中的分隔符不会在输出中显示为标记,而 keep_delims 中的分隔符确实显示为标记。
http://www.boost.org/doc/libs/1_55_0/libs/tokenizer/char_separator.htm

See next live:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

int main() {
    // added consecutive tokens for illustration
    std::string text = "I #am going to# learn how ####to use #boost# library#";    
    boost::char_separator<char> sep("", "#"); // specify only the kept separators
    boost::tokenizer<boost::char_separator<char>> tokens(text, sep);
    for (std::string t : tokens) { std::cout << "[" << t << "]" << std::endl; }
}
/* Output:
[I ]
[#]
[am going to]
[#]
[ learn how ]
[#]
[#]
[#]
[#]
[to use ]
[#]
[boost]
[#]
[ library]
[#] */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2022-11-03
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多