问题
对一个string类型的字符串进行分割,得到各个子字符串。
方法
有多种方法可以达到这个目的,每个方法都有利弊,根据项目实际情况选择即可。
1. 使用istream_iterator
std::string text = "Let me split this into words";
std::istringstream iss(text);
std::vector<std::string> results((std::istream_iterator<std::string>(iss)),
std::istream_iterator<std::string>());
优缺点:
- 示例使用了标准组件,跨平台,能够应用于各种形式的stream。
- 只能应用于空格,性能可以继续优化,有点大材小用
2. 使用 std::getline
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
优缺点:
- 接口清晰,能够应用于各种分隔符,且运行时指定
- 不是标准组件
3. 使用 boost::split
#include <boost/algorithm/string.hpp>
std::string text = "Let me split this into words";
std::vector<std::string> results;
boost::split(results, text, boost::is_any_of(" "));
//boost::split(results, text, [](char c){return c == ' ';});
boost::split的实现是使用多个find_if。如果输入的string的最后是指定的分隔符,结果的最后一个元素会是空string。
优缺点:
- 接口明显,可以使用各种分隔符,更快
- 需要安装boost库,结果不是通过返回值返回
4. 使用 string.find方法
string tmpstr = str;
while (tmpstr.find(" ") != string::npos) {
int found = tmpstr.find(" ");
v.push_back(tmpstr.substr(0, found));
tmpstr = tmpstr.substr(found + 1);
}
v.push_back(tmpstr);
总结
- 如果有boost可用,建议直接使用方法3
- 如果没有boost,可以使用方法2
- 如果只想使用标准组件,使用方法1
- 也可以使用find/find_if等方法自己实现