C++ 中是否有 PHP 的 expand() 函数的等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12966957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an equivalent in C++ of PHP's explode() function?
提问by reformed
Possible Duplicate:
Splitting a string in C++
可能的重复:
在 C++ 中拆分字符串
In PHP, the explode()function will take a string and chop it up into an array separating each element by a specified delimiter.
在 PHP 中,该explode()函数将接受一个字符串并将其分割成一个数组,用指定的分隔符分隔每个元素。
Is there an equivalent function in C++?
C++ 中是否有等效的函数?
回答by Kerrek SB
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.
注意:@Jerry 写入输出迭代器的想法对于 C++ 来说更为惯用。事实上,您可以同时提供两者;一个输出迭代器模板和一个生成向量的包装器,以获得最大的灵活性。
Note 2: If you want to skip empty tokens, add if (!token.empty()).
注 2:如果要跳过空标记,请添加if (!token.empty()).
回答by Jerry Coffin
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:
标准库不包含直接的等效项,但编写起来相当容易。作为 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;
}

