Created
January 28, 2020 22:14
-
-
Save ScottHutchinson/6b699c997a33c33130821922c11d25c3 to your computer and use it in GitHub Desktop.
A very fast split function in C++
This file contains 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
/* 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