Boost Solution :
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
Without boost :
1
string text = "you are so belle";vector<string> results; istringstream iss(text);copy(istream_iterator<string>(iss), istream_iterator<string>(), (back_inserter(results)));2
This is one solution but not effective : how to split with other symble? (, ; / ...)we need to redefine the >> operator :
istream& operator>>(istream& is, string& output){ // ...does lots of things...} |
class Mystring : public std::stringand then we can override our >> operator :
istream& operator>>(istream& is, MyString& output){ getline(is, output, ','); // we can split by "," return is;}3
can we do better ?Yes ! is that effective to override >> operator for every symble you want to split with ?
Solution is Template :
template<char delimiter>class Mystring: public std::string{};
-------------------------------
istream& operator>>(istream& is, Mystring<char delimiter>& output){ getline(is, output, delimiter); return is;}
--------------------------------
string text = "I want to split this into words";
vector<string> results;
istringstream iss(text);
copy(istream_iterator<WordDelimitedBy<';'> >(iss),
istream_iterator<WordDelimitedBy<';'> >(),
back_inserter(results));
voilà , in term of effecient : the solution boost is better than solution 3>2>1
No comments:
Post a Comment