There are a lot of terrible answers here, so I will add (including a test program):
#include <string> #include <iostream> #include <cstddef> template<typename StringFunction> void splitString(const std::string &str, char delimiter, StringFunction f) { std::size_t from = 0; for (std::size_t i = 0; i < str.size(); ++i) { if (str[i] == delimiter) { f(str, from, i); from = i + 1; } } if (from <= str.size()) f(str, from, str.size()); } int main(int argc, char* argv[]) { if (argc != 2) return 1; splitString(argv[1], ',', [](const std::string &s, std::size_t from, std::size_t to) { std::cout << "'" << s.substr(from, to - from) << "'\n"; }); return 0; }
Good properties:
- No dependencies (e.g. boost)
- Not crazy single line
- Easy to understand (hopefully)
- Handles spaces perfectly
- Does not highlight partitions if you do not want this, for example, you can process them using lambda, as shown.
- Does not add characters one at a time - should be fast.
- If you use C ++ 17, you can change it to use
std::stringview and then it will not make any allocations and should be very fast.
Some design options you might want to change:
- Blank entries are not ignored.
- An empty string will call f () once.
Examples of inputs and outputs:
"" -> {""} "," -> {"", ""} "1," -> {"1", ""} "1" -> {"1"} " " -> {" "} "1, 2," -> {"1", " 2", ""} " ,, " -> {" ", "", " "}
Timmmm Feb 15 '18 at 12:27 2018-02-15 12:27
source share