0

Possible Duplicate:
Splitting a string in C++

I need a function of split.

has to work like this:

buffer = split(str, ' ');

I searchead a split functions, tryed boost libs, and all works bad :/

Community
  • 1
  • 1
ernilos
  • 53
  • 1
  • 4

3 Answers3

1

strtok() from standard c library is pretty good and does what you are looking for. Unless you are keen on using it from multiple threads and worried about function not being re entrant which i don't suspect is the case here.

P.S. Above assumes you have a character array as input. If it was a c++ string, still you can use string.c_str to get the c string before using strtok

fkl
  • 5,412
  • 4
  • 28
  • 68
1

The boost lib is supposed to work as well.

Use it like so:

vector <string> buffer;
boost::split(buffer, str_to_split, boost::is_any_of(" "));

Added:
Make sure to include the algorithm:

#include <boost/algorithm/string.hpp>

Print it to the std::cout like so:

vector<string>::size_type sz = buffer.size();
cout << "buffer contains:";
for (unsigned i=0; i<sz; i++)
cout << ' ' << buffer[i];
cout << '\n';
Jon
  • 7,848
  • 1
  • 40
  • 41
Yarneo
  • 2,922
  • 22
  • 30
-1

I guess strtok() is what you're looking for.

It allows you to always return the first sub string delimited by given character(s):

char *string = "Hello World!";
char *part = strtok(string, " "); // passing a string starts a new iteration
while (part) {
    // do something with part
    part = strtok(NULL, " "); // passing NULL continues with the last string
}

Note that this version must not be used in several threads at once (there's also a version (strtok_s(), more details here) which has an additional parameter to make it work in a parallelized environment). This is also true for cases where you'd like to split a substring within a loop.

Community
  • 1
  • 1
Mario
  • 35,726
  • 5
  • 62
  • 78