Ad
Code
Diff
  • #include <string>
    #include <vector>
    #include <string_view>
    
    static constexpr size_t BUFFER_SIZE = 64;
    
    std::vector<std::string> split(std::string_view input, const char delimiter, bool strip = false) noexcept {
        std::vector<std::string> result;
        result.reserve(8);  // More reasonable initial size
        
        char buffer[BUFFER_SIZE];
        size_t bufferPos = 0;
        
        auto flushBuffer = [&]() {
            if (!strip || bufferPos > 0) {
                if (bufferPos < BUFFER_SIZE) {
                    result.emplace_back(buffer, bufferPos);
                } else {
                    result.emplace_back(std::string(buffer, bufferPos));
                }
            }
            bufferPos = 0;
        };
        
        for (const char c : input) {
            if (c == delimiter) {
                flushBuffer();
            } else if (bufferPos < BUFFER_SIZE) {
                buffer[bufferPos++] = c;
            }
        }
        
        flushBuffer();  // Handle the last token
        return result;
    }
    • #include <string>
    • #include <vector>
    • #include <string_view>
    • auto split(std::string_view s, const char d, bool strip = false) noexcept {
    • std::vector<std::string> r;
    • r.reserve(16);
    • char b[64];
    • int n = 0;
    • static constexpr size_t BUFFER_SIZE = 64;
    • std::vector<std::string> split(std::string_view input, const char delimiter, bool strip = false) noexcept {
    • std::vector<std::string> result;
    • result.reserve(8); // More reasonable initial size
    • char buffer[BUFFER_SIZE];
    • size_t bufferPos = 0;
    • for (auto c : s) {
    • if (c == d) {
    • if (!strip || n) {
    • if (n < 64) r.emplace_back(b, n);
    • else r.emplace_back(std::string(b, n));
    • auto flushBuffer = [&]() {
    • if (!strip || bufferPos > 0) {
    • if (bufferPos < BUFFER_SIZE) {
    • result.emplace_back(buffer, bufferPos);
    • } else {
    • result.emplace_back(std::string(buffer, bufferPos));
    • }
    • n = 0;
    • } else b[n++] = c;
    • }
    • }
    • bufferPos = 0;
    • };
    • if (!strip || n) {
    • if (n < 64) r.emplace_back(b, n);
    • else r.emplace_back(std::string(b, n));
    • for (const char c : input) {
    • if (c == delimiter) {
    • flushBuffer();
    • } else if (bufferPos < BUFFER_SIZE) {
    • buffer[bufferPos++] = c;
    • }
    • }
    • return r;
    • flushBuffer(); // Handle the last token
    • return result;
    • }