Skip to content

Instantly share code, notes, and snippets.

@Smail
Created March 9, 2024 02:40
Show Gist options
  • Select an option

  • Save Smail/a1c2dd42a2c2be44b6aa15fd5e3e3a2f to your computer and use it in GitHub Desktop.

Select an option

Save Smail/a1c2dd42a2c2be44b6aa15fd5e3e3a2f to your computer and use it in GitHub Desktop.
C++ String Split
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