Thursday, June 16, 2016

[C++] Your own string spliter

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...
}
But we cannot override this method! (why ? ) So , why not to create another method who takes MyString but not string:
class Mystring : public std::string
{};

and 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 Mystringpublic 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