在PHP中,explode()函数将接受一个字符串,并将其分割成一个数组,将每个元素通过指定的分隔符分隔开来。
在C++中有等效的函数吗?
发布于 2012-10-19 03:36:30
下面是一个简单的实现示例:
#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;
}用法:
auto v = explode("hello world foo bar", ' ');注意:@曾傑瑞编写输出迭代器的想法对于C++来说更为惯用。实际上,您可以同时提供输出迭代器模板和生成向量的包装器,以获得最大的灵活性。
注2:如果要跳过空令牌,请添加if (!token.empty())。
发布于 2012-10-19 03:36:47
标准库不包括直接的等价库,但编写起来相当容易。作为C++,您通常不希望专门写入数组--相反,您通常希望将输出写入迭代器,这样就可以将输出写入数组、向量、流等。这将提供一些关于一般顺序的内容:
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;
}https://stackoverflow.com/questions/12966957
复制相似问题