Created
May 17, 2023 08:40
-
-
Save ZJUGuoShuai/c5f65f54222b19eff12f04d3c4d78777 to your computer and use it in GitHub Desktop.
C++ 实现类似 Python 字符串的 split 函数
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 <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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我的和 DALI 的性能对比:https://quick-bench.com/q/ljKZItp5YvqVl0-EvrwpZDx1sSc