这是一个简单的实现示例:
#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", ' ');
注意:@Jerry提出的将结果写入输出迭代器的方法在C++中更加惯用。实际上,你可以同时提供一个输出迭代器模板和一个生成向量的包装器,以获得最大的灵活性。if (!token.empty())
。s.back() == delim
,则在这种情况下发出另一个空字符串。 - Kerrek SBvector<string> std::string::split(char delimiter = ' ');
- doctorram标准库中没有直接等价的函数,但它是一个相当容易编写的函数。由于是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;
}
std::getline
调用中存在错误。在你的代码中,我认为应该将input
更改为temp
。 - AntonioCSwhile (buffer >> temp)
。 - Jerry Coffin
boost::split
函数来自 boost/algorithm/string.hpp。 - Praetorian