C ++ tokenize std string

Possible duplicate:
How to make string tokenization in C ++?

Hello, I was wondering how I would designate a std string with strtok

string line = "hello, world, bye";    
char * pch = strtok(line.c_str(),",");

I get the following error

error: invalid conversion fromconst char*’ to ‘char*’
error: initializing argument 1 of ‘char* strtok(char*, const char*)’

I am looking for a quick and easy approach to this, as I don’t think it takes a long time

+5
source share
4 answers

I always use getlinefor such tasks.

istringstream is(line);
string part;
while (getline(is, part, ','))
  cout << part << endl;
+8
source
std::string::size_type pos = line.find_first_of(',');
std::string token = line.substr(0, pos);

to find the next token, repeat find_first_of, but start with pos + 1.

+7
source

strtok, &*line.begin(), char. boost::algorithm::split, ++.

+3

strtokis a pretty dodgy, evil function that modifies its argument. This means that you cannot use it directly in the content std::string, since there is no way to get a pointer to a mutable array of characters with a null character from this class.

You can work with a copy of string data:

std::vector<char> buffer(line.c_str(), line.c_str()+line.size()+1);
char * pch = strtok(&buffer[0], ",");

or, for the larger C ++ idiom, you can use a stream of strings:

std::stringstream ss(line);
std::string token;
std::readline(ss, token, ',');

or find a comma more directly:

std::string token(line, 0, line.find(','));
+1
source

All Articles