Is there an equivalent in C++ of PHP's explode() function? [duplicate]
Possible Duplicate:
Splitting a string in C++
In PHP, the explode()
function will take a string and chop it up into an array separating each element by a specified delimiter.
Is there an equivalent function in C++?
Here's a simple example implementation:
#include <string>
#include <vector>
#include <sstream>
#include <utility>
std::vector<std::string> explode(std::string const & s, char delim)
{
std::vector<std::string> result;
std::istringstream iss(s);
for (std::string token; std::getline(iss, token, delim); )
{
result.push_back(std::move(token));
}
return result;
}
Usage:
auto v = explode("hello world foo bar", ' ');
Note: @Jerry's idea of writing to an output iterator is more idiomatic for C++. In fact, you can provide both; an output-iterator template and a wrapper that produces a vector, for maximum flexibility.
Note 2: If you want to skip empty tokens, add if (!token.empty())
.
The standard library doesn't include a direct equivalent, but it's a fairly easy one to write. Being C++, you don't normally want to write specifically to an array though -- rather, you'd typically want to write the output to an iterator, so it can go to an array, vector, stream, etc. That would give something on this general order:
template <class OutIt>
void explode(std::string const &input, char sep, OutIt output) {
std::istringstream buffer(input);
std::string temp;
while (std::getline(buffer, temp, sep))
*output++ = temp;
}