split string into fields

Dec 10, 2011 at 1:37pm
Hi,

I need to split a string into a fields. The string is delimitted into fields with a comma (,). Do I have to extract each field via string operations like finding position to next delimitter and extracting appropriate substring or can I do it via something more elegant - I think recall seeing some mechanism where the string is split into a vector directly.

Can anyone please help me?
Dec 10, 2011 at 3:04pm
You could use getline, but the elegant solution you're looking for is a split function.
boost has one (boost::algorithm::split), although it's awkward to use.
You can use a wrapper for the common case, something along the lines of:
1
2
3
4
5
6
7
8
#include <boost/algorithm/string.hpp>
std::vector<std::string> explode(const std::string& str,char delim)
{
  std::vector<std::string> parts;
  char tmp[1]={delim};
  boost::algorithm::split(parts,str,boost::algorithm::is_any_of(tmp));
  return parts;
}


...or perhaps better, just write your own split function.
Dec 10, 2011 at 3:26pm
Dec 11, 2011 at 6:00am
Thanks for the responses - I will probably resort to writing my own and may then very well use strtok under the the hood for it. I'm reluctant to include boost into my project at this stage.

It would have been nice to have the boost type of solution in stl.


Dec 11, 2011 at 6:15am
You also can do this:
1
2
3
4
5
6
stringstream ss(inputString);
char delimiter = ',';
string token;
while(getline(ss, token, delimiter){
 //Analyze token
}
Dec 11, 2011 at 2:19pm
If you use Visual Studio or GCC you could use std::tr1::regex header, no need for boost.
Dec 11, 2011 at 2:26pm
tfityo +1

I generally use std::istringstream:
http://cplusplus.com/reference/iostream/istringstream/

And std::getline():
http://cplusplus.com/reference/string/getline/
Dec 11, 2011 at 6:45pm
Try the Boost String Algorithms library. It has a split function that will return a vector of strings.

You could also use the Boost Tokenizer library which provides an iterator interface; you can very easily construct a vector of strings with it.
Dec 11, 2011 at 8:08pm
Thanks for all the replies - I really appreciate it.

I think the best for my purposes would be to use getline with an istringsteam object.

I will definelty have a look a boost for subsequent projects.

Topic archived. No new replies allowed.