From c89aa61cca993b1c73cb5714c4260a1ade242785 Mon Sep 17 00:00:00 2001 From: Brett Laptop Date: Thu, 8 Feb 2024 14:08:09 -0500 Subject: [PATCH] string_view splits, with sv variants for returning vectors of views into the string_view --- include/blt/std/string.h | 60 ++++++++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/include/blt/std/string.h b/include/blt/std/string.h index d4b82b2..43ea9c9 100755 --- a/include/blt/std/string.h +++ b/include/blt/std/string.h @@ -216,31 +216,67 @@ namespace blt::string // taken from https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c // extended to return a vector - static inline BLT_CPP20_CONSTEXPR std::vector split(std::string s, std::string_view delim) + static inline BLT_CPP20_CONSTEXPR std::vector split(std::string_view s, std::string_view delim) { size_t pos = 0; + size_t from = 0; std::vector tokens; - while ((pos = s.find(delim)) != std::string::npos) + while ((pos = s.find(delim, from)) != std::string::npos) { - auto token = s.substr(0, pos); - tokens.push_back(token); - s.erase(0, pos + delim.length()); + auto size = pos - from; + auto token = s.substr(from, size); + tokens.emplace_back(token); + from += size + delim.length(); } - tokens.push_back(std::move(s)); + tokens.emplace_back(s.substr(from)); + return tokens; + } + + static inline BLT_CPP20_CONSTEXPR std::vector split(std::string_view s, char delim) + { + size_t pos = 0; + size_t from = 0; + std::vector tokens; + while ((pos = s.find(delim, from)) != std::string::npos) + { + auto size = pos - from; + auto token = s.substr(from, size); + tokens.emplace_back(token); + from += size + 1; + } + tokens.emplace_back(s.substr(from)); return tokens; } - static inline BLT_CPP20_CONSTEXPR std::vector split(std::string s, char delim) + static inline BLT_CPP20_CONSTEXPR std::vector split_sv(std::string_view s, std::string_view delim) { size_t pos = 0; - std::vector tokens; - while ((pos = s.find(delim)) != std::string::npos) + size_t from = 0; + std::vector tokens; + while ((pos = s.find(delim, from)) != std::string::npos) { - auto token = s.substr(0, pos); + auto size = pos - from; + auto token = s.substr(from, size); tokens.push_back(token); - s.erase(0, pos + 1); + from += size + delim.length(); } - tokens.push_back(s); + tokens.push_back(s.substr(from)); + return tokens; + } + + static inline BLT_CPP20_CONSTEXPR std::vector split_sv(std::string_view s, char delim) + { + size_t pos = 0; + size_t from = 0; + std::vector tokens; + while ((pos = s.find(delim, from)) != std::string::npos) + { + auto size = pos - from; + auto token = s.substr(from, size); + tokens.push_back(token); + from += size + 1; + } + tokens.push_back(s.substr(from)); return tokens; }