Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Created May 17, 2023 08:40
Show Gist options
  • Select an option

  • Save ZJUGuoShuai/c5f65f54222b19eff12f04d3c4d78777 to your computer and use it in GitHub Desktop.

Select an option

Save ZJUGuoShuai/c5f65f54222b19eff12f04d3c4d78777 to your computer and use it in GitHub Desktop.
C++ 实现类似 Python 字符串的 split 函数
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> split_naive(const std::string& s, char delim) {
std::vector<std::string> ret;
std::string token;
for (char ch : s) {
if (ch == delim) {
ret.push_back(token);
token.clear();
} else {
token += ch;
}
}
ret.push_back(token);
return ret;
}
void print_vector(const std::vector<std::string>& v) {
std::cout << "[";
if (v.size() > 0) {
std::cout << "'" << v[0] << "'";
}
for (size_t i = 1; i < v.size(); i++) {
std::cout << ", '" << v[i] << "'";
}
std::cout << "]\n";
}
int main() {
std::string test = ",123,,456,";
std::vector<std::string> tokens = split_naive(test, ',');
print_vector(tokens);
return 0;
}
@ZJUGuoShuai

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment