【问题标题】:c++ boost split stringc++ boost 分割字符串
【发布时间】:2011-08-09 17:02:38
【问题描述】:

我正在使用boost::split 方法将字符串拆分为:

我首先确保包含正确的标题以访问boost::split

#include <boost/algorithm/string.hpp>

然后:

vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

线条就像

"test   test2   test3"

这就是我使用结果字符串向量的方式:

void printstrs(vector<string> strs)
{
    for(vector<string>::iterator it = strs.begin();it!=strs.end();++it)
    {
        cout << *it << "-------";
    }

    cout << endl;
}

但是为什么在结果strs我只得到"test2""test3",不应该是"test""test2""test3",字符串中有\t(制表符)。

2011 年 4 月 24 日更新: 似乎在我更改 printstrs 的一行代码后,我可以看到第一个字符串。我变了

cout << *it << "-------";

cout << *it << endl;

似乎"-------" 以某种方式覆盖了第一个字符串。

【问题讨论】:

  • 展示你如何使用向量。我猜问题就在那里。
  • boost::is_any_of("\t") 的效率不如[](char c) { return c=='\t';}。您只想检查一种可能性。 (不知道为什么没有boost:is('\t')
  • @MSalters 注释中的代码是什么意思?如何使用该代码替换 boost::is_any_of()
  • @PoscoGrubb:它被称为“lambda”,boost::splits 理解它们。

标签: c++ boost split


【解决方案1】:

问题出在代码中的其他地方,因为这样可以:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

并测试您使用矢量迭代器的方法也可以:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

同样,您的问题出在其他地方。也许您认为字符串上的 \t 字符不是。我会用调试填充代码,首先监视向量上的插入,以确保所有内容都按照预期的方式插入。

输出:

* size of the vector: 3
test
test2
test3

【讨论】:

  • 如果您不分享重现您所面临问题的最小示例,我们无能为力。请记住:最小示例,而不是完整的应用程序。
  • 谢谢。似乎我将 cout
  • 仅供参考,此示例中使用了以下 Boost 标头:#include &lt;boost/algorithm/string/split.hpp&gt;#include &lt;boost/algorithm/string/classification.hpp&gt;
  • 这不起作用。尝试string = "hih1ihi" 和substring = "hi。工作结果不正确。
【解决方案2】:

我最好的猜测是为什么您在覆盖您的第一个结果时遇到问题 ----- 是您实际上是从文件中读取了输入行。该行的末尾可能有一个 \r 所以你最终得到了这样的东西:

-----------test2-------test3

机器实际打印了这个:

test-------test2-------test3\r-------

这意味着,由于 test3 末尾的回车,test3 之后的破折号打印在第一个单词的顶部(以及 test 和 test2 之间的一些现有破折号,但您不会注意到因为它们已经是破折号了)。

【讨论】:

    【解决方案3】:
    template <class Container>
    void split1(const std::string& str, Container& cont)
    {
       boost::algorithm::split_regex(cont, str, boost::regex("\t"));
    }
    
    std::vector<std::string> vec1;
    std::string str = "hest1\twest2\tpiest3";
    split1(str, vec1);
    

    vec == ("hest1","west2","piest3")

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2015-01-21
      相关资源
      最近更新 更多