From 3dccac62b7dea16d13aa85e73bfd75eb57857b1d Mon Sep 17 00:00:00 2001 From: tqcq <99722391+tqcq@users.noreply.github.com> Date: Sun, 3 Mar 2024 00:46:50 +0800 Subject: [PATCH] feat add StrJoin --- CMakeLists.txt | 1 + include/sled/strings/utils.h | 9 +++++++-- src/strings/utils.cc | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 src/strings/utils.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index d512a80..a1364ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,6 +28,7 @@ target_sources( src/network/socket_address.cc src/network/socket_server.cc src/strings/base64.cc + src/strings/utils.cc src/synchronization/event.cc src/synchronization/mutex.cc src/synchronization/sequence_checker_internal.cc diff --git a/include/sled/strings/utils.h b/include/sled/strings/utils.h index a1dddda..d2724ed 100644 --- a/include/sled/strings/utils.h +++ b/include/sled/strings/utils.h @@ -1,10 +1,15 @@ #ifndef SLED_STRINGS_UTILS_H #define SLED_STRINGS_UTILS_H +#include + namespace sled { std::string ToLower(const std::string &str); std::string ToUpper(const std::string &str); std::string ToHex(const std::string &str); +std::string StrJoin(const std::vector &strings, + const std::string &delim, + bool skip_empty = false); -} // namespace sled -#endif // SLED_STRINGS_UTILS_H +}// namespace sled +#endif// SLED_STRINGS_UTILS_H diff --git a/src/strings/utils.cc b/src/strings/utils.cc new file mode 100644 index 0000000..3061c03 --- /dev/null +++ b/src/strings/utils.cc @@ -0,0 +1,23 @@ +#include "sled/strings/utils.h" +#include + +namespace sled { + +std::string +StrJoin(const std::vector &strings, + const std::string &delim, + bool skip_empty) +{ + if (strings.empty()) { return ""; } + + std::stringstream ss; + size_t i = 0; + while (skip_empty && i < strings.size() && strings[i].empty()) { ++i; } + if (i < strings.size()) { ss << strings[i++]; } + for (; i < strings.size(); ++i) { + if (skip_empty && strings[i].empty()) { continue; } + ss << delim << strings[i]; + } + return ss.str(); +} +}// namespace sled