Igor Tupitsyn
Igor Tupitsyn

Reputation: 1193

C++ tokenize a string with boost and save a token as a string

I need to split a string into tokens and return the third token as a string.

I have the following code:

    #include <iostream>
    #include <string>
    #include <cstring>
    #include <boost/tokenizer.hpp>
    #include <fstream>
    #include <sstream>

    using namespace std;

    main()
    {
           std::string line = "Data1|Data2|Data3|Data4|Data5"; 

           typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

           boost::char_separator<char> sep("|");

           tokenizer tokens(line, sep);

           for (tokenizer::iterator tok_iter = tokens.begin();
                    tok_iter != tokens.end(); ++tok_iter)

           std::cout << *tok_iter << endl;
           std::cout << "\n";
      }

The code nicely separates the string into tokens. Now I cannot figure out how I can save the third token, for instance, as a separate string.

Thanks!

Upvotes: 3

Views: 5330

Answers (1)

Eric Z
Eric Z

Reputation: 14505

Just store to a string when you know it's the 3rd iteration of the loop. You don't need any extra variable with the help of std::distance.

   string str;
   for (tokenizer::iterator tok_iter = tokens.begin();
      tok_iter != tokens.end(); ++tok_iter)
   {
      // if it's the 3rd token
      if (distance(tokens.begin(), tok_iter) == 2)
      {
         str = *tok_iter;
         // prints "Data3"
         cout << str << '\n';
      }
   }

Upvotes: 4

Related Questions