Splitting a string in C++

Monday, January 07, 2013 , , , 2 Comments

Once I writing a tool for processing some  csv files where in I needed to split strings and store them in a vector.I wrote one function for it which i feel like sharing.below is the function to split the string:
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}

The given function splits the string and returns a vector of strings.Also i would like to mention that if the string contains empty fields then an empty element  is inserted into the vector.

More simple way would be:
#include <sstream>//for std::istringstream
#include <iterator> //for std::istream_iterator
#include <vector>//for std::vector
while(std::getline(in, line))
{
std::istringstream ss(line);
std::istream_iterator<std::string> begin(ss), end;//putting all the tokens in the vector std::vector<std::string> arrayTokens(begin, end);//arrayTokens is containing all the tokens - use it!
}

2 comments:

  1. Why not use BOOST tokenizer? @see reference below.
    http://www.boost.org/doc/libs/1_53_0/libs/tokenizer/

    ReplyDelete
  2. Yeah adam boost can be used. but in caseif anybody dont want to use boost they can use this.

    ReplyDelete