Created
June 14, 2022 03:12
-
-
Save LessUp/cb1bde29fb296b82f05cec284a798068 to your computer and use it in GitHub Desktop.
[分割字符串] #split #c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <string> | |
| #include <vector> | |
| #include <iostream> | |
| using namespace std; | |
| void split(const string &s, vector<string> &tokens, const string &delimiters = " ") { | |
| string::size_type lastPos = s.find_first_not_of(delimiters, 0); | |
| string::size_type pos = s.find_first_of(delimiters, lastPos); | |
| while (string::npos != pos || string::npos != lastPos) { | |
| tokens.push_back(s.substr(lastPos, pos - lastPos)); // use emplace_back after C++11 | |
| lastPos = s.find_first_not_of(delimiters, pos); | |
| pos = s.find_first_of(delimiters, lastPos); | |
| } | |
| } | |
| int main() { | |
| string s1 = "1 2 3 4 5"; | |
| vector<string> field; | |
| split(s1, field); | |
| for (auto &i: field) { | |
| cout << i << endl; | |
| } | |
| string s2 = "1,2,3,4,5"; | |
| field = vector<string>(); | |
| split(s2, field); | |
| for (auto &i: field) { | |
| cout << i << endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment