Is there an equivalent in C++ of PHP's explode() function?

reformed picture reformed · Oct 19, 2012 · Viewed 34.5k times · Source

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++?

Answer

Kerrek SB picture Kerrek SB · Oct 19, 2012

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()).