-5
getline(cin,s);
istringstream iss(s);
do
{
    string sub;
    iss>>sub;
    q.insert(sub);
 }while(iss);

I used this technique when question wanted me to split on the basis of space so can anyone explain me how to split when there's a particular delimiter like ';' or ':'.

Someone told me about strtok function but i am not able to get it's usage so it would be nice if someone could help.

James Mills
  • 18,669
  • 3
  • 49
  • 62
vs13
  • 13
  • 2
  • 4
  • 1
    Check http://stackoverflow.com/a/236803/1170333 – prajmus Jun 20 '14 at 12:51
  • 2
    The most efficient way is to SEARCH this information at StackOverflow. Thiis has been answered before. – harper Jun 20 '14 at 12:54
  • The most efficient way is to SEARCH this information at Google. (@harper upvoted) – Orelsanpls Jun 20 '14 at 12:55
  • @vs13 In future before asking a question you might want to be informed [about this](http://stackoverflow.com/help/how-to-ask) – πάντα ῥεῖ Jun 20 '14 at 13:04
  • Thanks @πάνταῥεῖ will keep this in mind. – vs13 Jun 20 '14 at 13:06
  • 1
    I implemented a [delimited input stream iterator](https://gist.github.com/sftrabbit/4335b21717fff8f8932a). To use, fill a `std::istringstream` with your string, then do: `std::vector split{delim_istream_iterator<>{ss, ':'}, delim_istream_iterator<>{}};`. Replace `:` with whatever your delimiter is. – Joseph Mansfield Jun 20 '14 at 14:03

1 Answers1

17

First, don't use strtok. Ever.

There's not really a function for this in the standard library. I use something like:

std::vector<std::string>
split( std::string const& original, char separator )
{
    std::vector<std::string> results;
    std::string::const_iterator start = original.begin();
    std::string::const_iterator end = original.end();
    std::string::const_iterator next = std::find( start, end, separator );
    while ( next != end ) {
        results.push_back( std::string( start, next ) );
        start = next + 1;
        next = std::find( start, end, separator );
    }
    results.push_back( std::string( start, next ) );
    return results;
}

I believe Boost has a number of such functions. (I implemented most of mine long before there was Boost.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329