diff --git a/server/src/utils/string.cpp b/server/src/utils/string.cpp index b8ff70f..475d535 100644 --- a/server/src/utils/string.cpp +++ b/server/src/utils/string.cpp @@ -32,3 +32,63 @@ std::string* sosc::str::rtrim(std::string *str) { str->erase(str->length() - marker - 1, marker); return str; } + +std::vector sosc::str::split + (const std::string& str, char delimiter, int count) +{ + std::string buffer; + std::stringstream stream(str); + auto parts = std::vector(); + + --count; + while(count != 0) { + if(!std::getline(stream, buffer, delimiter)) + break; + + parts.push_back(buffer); + --count; + } + + if(std::getline(stream, buffer)) + parts.push_back(buffer); + return parts; +} + +std::vector sosc::str::split + (const std::string& str, std::string delimiter, int count) +{ + auto parts = std::vector(); + std::size_t chunk_end = 0, chunk_start = 0; + + --count; + while((chunk_end = str.find(delimiter, chunk_end)) + != std::string::npos && count != 0) + { + parts.push_back(str.substr(chunk_start, chunk_start - chunk_end)); + chunk_start = (chunk_end += delimiter.length()); + --count; + } + + parts.push_back(str.substr(chunk_start, std::string::npos)); + return parts; +} + +std::string sosc::str::join(const std::vector& parts, + char delimiter, int count) +{ + return join(parts, std::string(1, delimiter), count); +} + +std::string sosc::str::join(const std::vector& parts, + std::string delimiter, int count) +{ + std::string assembled; + int bounds = (count == -1) + ? parts.size() + : std::min(count, parts.size()); + + for(int i = 0; i < bounds; ++i) + assembled += (i == 0 ? "" : delimiter) + parts[i]; + + return assembled; +} diff --git a/server/src/utils/string.hpp b/server/src/utils/string.hpp index 1ceef38..d65ef3a 100644 --- a/server/src/utils/string.hpp +++ b/server/src/utils/string.hpp @@ -3,9 +3,11 @@ #include #include +#include +#include namespace sosc { -namespace str { +namespace str { std::string trim (std::string str); std::string* trim (std::string* str); @@ -20,9 +22,9 @@ std::vector split std::vector split (const std::string& str, std::string delimiter, int count = -1); -std::string join(const std::vector& strs, +std::string join(const std::vector& parts, char delimiter, int count = -1); -std::string join(const std::vector& strs, +std::string join(const std::vector& parts, std::string delimiter, int count = -1); }}