C++标准库STL 之 我觉得应该有的方法——split
vector<string> split(const string& s, const string& c) { vector<string> result; string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while (string::npos != pos2) { result.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) { result.push_back(s.substr(pos1)); } return result; }
使用示例
#include <iostream> #include <string> #include <vector> int main() { string str = "Hello wooold ahh!"; vector<string> v = split(str," "); for (string::size_type i = 0; i < v.size(); ++i) { cout << v[i] << endl; } return 0; }
输出
Hello
wooold
ahh!