Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c++ boost split string

I'm using the boost::split method to split a string as this:

I first make sure to include the correct header to have access to boost::split:

#include <boost/algorithm/string.hpp>

then:

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

and the line is like

"test   test2   test3"

This is how I consume the result string vector:

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

    cout << endl;
}

But why in the result strs I only get "test2" and "test3", shouldn't be "test", "test2" and "test3", there are (tab) in the string.

Updated Apr 24th, 2011: It seemed after I changed one line of code at printstrs I can see the first string. I changed

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

to

cout << *it << endl;

And it seemed "-------" covered the first string somehow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is somewhere else in your code, because this works:

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

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

and testing your approach, which uses a vector iterator also works:

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

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

Again, your problem is somewhere else. Maybe what you think is a character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...