Created
March 9, 2024 02:40
-
-
Save Smail/a1c2dd42a2c2be44b6aa15fd5e3e3a2f to your computer and use it in GitHub Desktop.
C++ String 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
| constexpr std::vector<std::string> split(const std::string& str, std::string_view delimiter = " ") { | |
| std::vector<std::string> xs{}; | |
| int start = 0; | |
| int end = 0; | |
| int delimiter_index = 0; | |
| for (; end < str.size(); ++end) { | |
| if (str[end] != delimiter[delimiter_index]) [[likely]] { | |
| end -= delimiter_index; | |
| delimiter_index = 0; | |
| continue; | |
| } | |
| if (++delimiter_index == delimiter.size()) [[unlikely]] { | |
| if (auto length = end - start - delimiter.size() + 1; length > 0) { | |
| xs.push_back(str.substr(start, length)); | |
| } | |
| start = end + 1; | |
| delimiter_index = 0; | |
| } | |
| } | |
| if (start < end) xs.push_back(str.substr(start)); | |
| return xs; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment