From 719697eabe6442f7aaa1468b8a789944aec4c3f8 Mon Sep 17 00:00:00 2001 From: Gwenhael Goavec-Merou Date: Tue, 18 Mar 2025 22:39:44 +0100 Subject: [PATCH] common: added function to split a string to a vector by using a delimiter --- src/common.cpp | 20 ++++++++++++++++++++ src/common.hpp | 9 +++++++++ 2 files changed, 29 insertions(+) diff --git a/src/common.cpp b/src/common.cpp index fcf6975..6547913 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -19,3 +19,23 @@ const std::string get_shell_env_var(const char* key, const char* ret = std::getenv(key); return std::string(ret ? ret : def_val); } + +/*! + * \brief convert a string, separate by delim to a vector + * \param[in] in: string to split + * \param[in] delim: split caracter + * \return vector a substring + */ +const std::vector splitString(const std::string& in, + const char delim) noexcept { + std::vector tokens; + size_t start = 0, end = 0; + + while ((end = in.find(',', start)) != std::string::npos) { + tokens.push_back(in.substr(start, end - start)); + start = end + 1; + } + + tokens.push_back(in.substr(start)); // Add the last token + return tokens; +} diff --git a/src/common.hpp b/src/common.hpp index d85ded8..0ec85d1 100644 --- a/src/common.hpp +++ b/src/common.hpp @@ -17,4 +17,13 @@ const std::string get_shell_env_var(const char* key, const char *def_val="") noexcept; +/*! + * \brief convert a string, separate by delim to a vector + * \param[in] in: string to split + * \param[in] delim: split caracter + * \return vector a substring + */ +const std::vector splitString(const std::string& in, + const char delim) noexcept; + #endif // SRC_COMMON_HPP_