比较了网上的一些split实现方法,比较喜欢利用 string 自带函数 find 和 substr 组合实现的方法,记录下。
参考:C++如何做字符串分割(5种方法)_听风雨-CSDN博客_c++分割字符串
std::vector<std::string> split(std::string str, std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str += pattern; //扩展字符串以方便操作 不想扩充可以看下面那个 int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { std::string s = str.substr(i, pos - i); result.push_back(s); i = pos + pattern.size() - 1; // - 1 是因为 之后会for循环 ++i } } return result; }
参考: C++常见问题: 字符串分割函数 split - dfcao - 博客园 (cnblogs.com)
void SplitString(const std::string &s, std::vector<std::string> &v, const std::string &c) { std::string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while (std::string::npos != pos2) { v.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) v.push_back(s.substr(pos1)); }
find()函数解释:C++ string中的find()函数 - 王陸 - 博客园 (cnblogs.com)
substr()函数解释:C++中string如何实现字符串分割函数split()_灰猫-CSDN博客_c++ string分割字符串split
C++ 的 string 为什么不提供 split 函数?:
C++ 的 string 为什么不提供 split 函数? - 知乎 (zhihu.com)