c ++ boost split string

时间:2011-04-20 17:34:38

标签: c++ boost split

我正在使用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;

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

3 个答案:

答案 0 :(得分:68)

问题出在您的代码中的其他位置,因为这有效:

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

答案 1 :(得分:12)

我最好猜测为什么你遇到第一个结果的问题是你实际从文件中读取输入行。该行最后可能有一个\ r \ n,所以你最终会得到这样的结果:

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

发生了什么事,机器实际打印了这个:

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

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

答案 2 :(得分:0)

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","pest3")