Is there an equivalent in C++ of PHPs explode() function?

Is there an equivalent in C++ of PHPs explode() function?

Heres 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: @Jerrys 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 doesnt include a direct equivalent, but its a fairly easy one to write. Being C++, you dont normally want to write specifically to an array though — rather, youd 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;
}

Is there an equivalent in C++ of PHPs explode() function?

Leave a Reply

Your email address will not be published.