Skip to content

Instantly share code, notes, and snippets.

@ScottHutchinson
Created January 28, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottHutchinson/6b699c997a33c33130821922c11d25c3 to your computer and use it in GitHub Desktop.
Save ScottHutchinson/6b699c997a33c33130821922c11d25c3 to your computer and use it in GitHub Desktop.
A very fast split function in C++
/* Based on http://www.cplusplus.com/forum/beginner/114790/#msg626659
and https://github.com/fenbf/StringViewTests/blob/master/StringViewTest.cpp#L151,
which is the repo for this blog post: https://www.bfilipek.com/2018/07/string-view-perf-followup.html
*/
template<typename Out = std::vector<std::string>>
Out split(const std::string_view s, const char delim, const size_t maxFields = 0) {
Out elems;
size_t start{};
size_t end{};
size_t numFieldsParsed{};
do {
end = s.find_first_of(delim, start);
elems.emplace_back(s.substr(start, end - start));
start = end + 1;
} while (end != std::string::npos && (maxFields == 0 || ++numFieldsParsed < maxFields));
return elems;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment