Skip to content

Instantly share code, notes, and snippets.

@LessUp
Created June 14, 2022 03:12
Show Gist options
  • Select an option

  • Save LessUp/cb1bde29fb296b82f05cec284a798068 to your computer and use it in GitHub Desktop.

Select an option

Save LessUp/cb1bde29fb296b82f05cec284a798068 to your computer and use it in GitHub Desktop.
[分割字符串] #split #c++
#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