I have a string and I want to split it every time the char ',' appears. I want to save the result in a vector of pointers to string. What is the best way to do this?
Asked
Active
Viewed 2,651 times
3 Answers
0
Or write your own. This algorithm is pretty easy to write in terms of std::find
.

Billy ONeal
- 104,103
- 58
- 317
- 552
0
"i want to split it every time that the char ','
..."
Use std::getline
and specify the delimiter (last argument) to be ','
.
"I want to save the result in a vector of pointers to string"
You want to avoid using vector of pointers, believe me. Use std::vector<std::string>
instead:
std::istringstream is(",,,my,,weird,string");
std::vector<std::string> tokens;
std::string token;
while (std::getline(is, token, ',')) {
if (!token.empty())
tokens.push_back(token);
}
for (int i = 0; i < tokens.size(); ++i)
std::cout << tokens[i] << " ";
outputs my weird string
. Just don't forget to #include <sstream>
.

LihO
- 41,190
- 11
- 99
- 167
0
I've used strtok
to tokenize string, but this has a few drawbacks:
- This is part of
cstring
and it's used for C-style strings, and notstd::string
objects. - It's kind of clumsy in terms of having to call it several times changing the parameter after the first time.
It's not ideal if you have boost available but it should work for all implementations of C++.

austin
- 5,816
- 2
- 32
- 40