diff --git a/misc/pstring.cpp b/misc/pstring.cpp index b6fa28e7..53a120cd 100644 --- a/misc/pstring.cpp +++ b/misc/pstring.cpp @@ -1,5 +1,5 @@ /* -* Descent 3 +* Descent 3 * Copyright (C) 2024 Parallax Software * * This program is free software: you can redistribute it and/or modify @@ -39,9 +39,11 @@ */ #include +#include +#include +#include #include "pstring.h" -#include // CleanupStr // This function strips all leading and trailing spaces, keeping internal spaces. This goes for tabs too. @@ -77,3 +79,32 @@ std::size_t CleanupStr(char *dest, const char *src, std::size_t destlen) { return out_size; } + +std::string StringJoin(const std::vector &strs, const std::string &delim) { + if (strs.empty()) + return ""; + std::vector res; + for (int i = 0; i < strs.size() - 1; ++i) { + for (auto const &c : strs[i]) { + res.push_back(c); + } + for (auto const &c : delim) { + res.push_back(c); + } + } + for (auto const &c : strs[strs.size() - 1]) { + res.push_back(c); + } + return std::string{res.begin(), res.end()}; +} + +std::vector StringSplit(std::string str, const std::string &delim) { + std::vector res; + size_t pos; + while ((pos = str.find(delim)) != std::string::npos) { + res.push_back(str.substr(0, pos)); + str.erase(0, pos + delim.length()); + } + res.push_back(str); + return res; +} diff --git a/misc/pstring.h b/misc/pstring.h index 1201ff7d..47fb4d2f 100644 --- a/misc/pstring.h +++ b/misc/pstring.h @@ -39,9 +39,17 @@ #define PSTRING_H #include +#include +#include // CleanupStr // This function strips all leading and trailing spaces, keeping internal spaces. This goes for tabs too. std::size_t CleanupStr(char *dest, const char *src, std::size_t destlen); +/** Joins a vector of strings into a single string */ +std::string StringJoin(const std::vector &strs, const std::string &delim); + +/** Splits str into vector of substrings */ +std::vector StringSplit(std::string str, const std::string &delim); + #endif diff --git a/misc/tests/misc_tests.cpp b/misc/tests/misc_tests.cpp index 7b5568ac..bec3dc77 100644 --- a/misc/tests/misc_tests.cpp +++ b/misc/tests/misc_tests.cpp @@ -41,3 +41,17 @@ TEST(D3, CleanupStr) { ASSERT_STREQ(result, i.second); } } + +TEST(D3, StringJoinSplit) { + std::string test = "Joined text;Another text;And more;"; + std::vector parts = {"Joined text", "Another text", "And more", ""}; + + std::string empty = ""; + std::vector empty_parts = {""}; + + ASSERT_EQ(test, StringJoin(parts, ";")); + ASSERT_EQ(StringSplit(test, ";"), parts); + + ASSERT_EQ(empty, StringJoin(empty_parts, ";")); + ASSERT_EQ(StringSplit(empty, ";"), empty_parts); +}