Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- std::vector<std::string> split(const std::string& str, const std::string& delimiter, bool ignore_empty, bool strip_spaces)
- {
- if (str.empty()) {
- return {};
- }
- std::vector<std::string> res;
- for (size_t p = 0, q = 0; p < str.length(); ++p) {
- if (delimiter.empty()) {
- res.push_back(std::string(1, str[p]));
- continue;
- }
- // If we are looking at the last character we want to check if the
- // remainder needs to be pushed into the result below, otherwise always
- // check for the delimiter first.
- if (p + 1 < str.length() &&
- str.compare(p, delimiter.length(), delimiter) != 0) {
- continue;
- }
- if (p == q) {
- // An empty fragment.
- if (!ignore_empty) {
- res.push_back("");
- }
- q += delimiter.length();
- } else {
- // Maybe an empty fragment
- std::string sub = str.substr(q, p - q);
- if (strip_spaces) {
- strip(sub);
- }
- if (!ignore_empty || !sub.empty()) {
- res.push_back(std::move(sub));
- }
- q = p + delimiter.length();
- }
- }
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment