Is there an equivalent in C++ of PHP’s explode() function? [duplicate]

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); )

    return result;


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

Leave a Comment