【问题标题】:split using boost::is_any_of confuses over delimeter ",," and ","使用 boost::is_any_of 拆分会混淆分隔符 ",," 和 ","
【发布时间】:2013-04-01 17:13:43
【问题描述】:

我目前有一个具有以下结构的字符串

xxx,xxx,xxxxxxx,,xxxxxx,xxxx

现在我使用下面的代码

 std::vector< std::string > vct;
 boost::split( vct, str, boost::is_any_of(",,") );

现在 boost 一旦找到“,”而不是“,”,就会拆分字符串,这是我不想要的。有什么方法可以明确指定它只有在找到“,”而不是“,”时才应该拆分

【问题讨论】:

  • is_any_of 的全部意义在于表示您提供的字符串中的任何一个字符。如果那不是你想要的,那就不要使用它。

标签: c++ boost


【解决方案1】:

is_any_of(",,") 将匹配列表中指定的任何内容。在这种情况下,,,

你要找的是沿线

boost::algorithm::split_regex( vct, str, regex( ",," ) ) ;

【讨论】:

  • 我认为你把它弄反了:它匹配 ,,,而不是 ,,
【解决方案2】:

供以后参考..

boost::split 采用第四个参数eCompress,可以让您将相邻的分隔符视为单个分隔符:

eCompress

如果 eCompress 参数设置为 token_compress_on,相邻 分隔符合并在一起。否则,每两个分隔符 划定一个标记。

您所要做的就是指定参数。你也可以跳过第二个,,如下:

boost::split( vct, str, boost::is_any_of(","),
              boost::algorithm::token_compress_on)

Here's the documentation.

【讨论】:

    【解决方案3】:

    Is_any_of 拆分字符串中的任何字符。它不会做你想做的事。您需要在 boost 手册中查找另一个谓词。

    编辑:出于好奇,我自己去查看 API,不幸的是我找不到你想要的现成谓词。最坏的情况是你必须自己写。

    【讨论】:

      【解决方案4】:
      #include <functional>
      #include <boost/algorithm/string/compare.hpp>
      ...
      
      std::vector< std::string > vct;
      //boost::split( vct, str, [](const auto& arg) { return arg == str::string(",,"); } );
      boost::split( vct, str, std::bind2nd(boost::is_equal, std::string(",,")) );
      

      【讨论】:

        猜你喜欢
        • 2011-07-04
        • 1970-01-01
        • 2014-03-18
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 1970-01-01
        相关资源
        最近更新 更多