使用stringstream + getline
使用getline进行分割
局限性,只能以单个字符作为分割线
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <string> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main(){ istringstream ss("helloahelloahello"); string word; char delim = 'a'; while(getline(ss,word,delim)){ cout<<word<<endl; } }
|
使用std::string::find
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <iostream> #include <sstream> #include <vector>
using namespace std;
vector<string> split (const string& s, const string& delimiter) { size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; vector<string> res;
while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { token = s.substr (pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; if(!token.empty()) res.push_back (token); } if(pos_start != s.size()) res.push_back (s.substr (pos_start)); return res; }
int main() { string str = "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih"; string delimiter = "-+"; vector<string> v = split (str, delimiter);
for (auto i : v) cout << i << endl;
return 0; }
|