23

可能重复:
在 C++ 中拆分字符串

在 PHP 中,该explode()函数将获取一个字符串并将其分割成一个数组,通过指定的分隔符分隔每个元素。

C++ 中有没有等价的函数?

4

2 回答 2

36

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

于 2012-10-19T03:36:30.563 回答
12

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;
}
于 2012-10-19T03:36:47.173 回答