Split a string in C++11

The example below works just like PHP's explode.

std::vector<std::string> tokenize(const std::string& s, char c) {
    auto end = s.cend();
    auto start = end;

    std::vector<std::string> v;
    for( auto it = s.cbegin(); it != end; ++it ) {
        if( *it != c ) {
            if( start == end )
                start = it;
            continue;
        }
        if( start != end ) {
            v.emplace_back(start, it);
            start = end;
        }
    }
    if( start != end )
        v.emplace_back(start, end);
    return v;
}

Usage:

auto v = tokenize(" abc  def ", ' ');

v == std::vector<std::string>{"abc", "def"}; // true

Simple and efficient.

Remove all ads