MISC: Add StringJoin() and StringSplit() functions

Added new functions for std::string manipulation.
This commit is contained in:
Azamat H. Hackimov 2024-07-16 15:40:01 +03:00
parent 233dc8bb39
commit 8943c676a1
3 changed files with 55 additions and 2 deletions

View File

@ -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 <cctype>
#include <cstdint>
#include <string>
#include <vector>
#include "pstring.h"
#include <cstdint>
// 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<std::string> &strs, const std::string &delim) {
if (strs.empty())
return "";
std::vector<char> 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<std::string> StringSplit(std::string str, const std::string &delim) {
std::vector<std::string> 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;
}

View File

@ -39,9 +39,17 @@
#define PSTRING_H
#include <cstring>
#include <string>
#include <vector>
// 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<std::string> &strs, const std::string &delim);
/** Splits str into vector of substrings */
std::vector<std::string> StringSplit(std::string str, const std::string &delim);
#endif

View File

@ -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<std::string> parts = {"Joined text", "Another text", "And more", ""};
std::string empty = "";
std::vector<std::string> empty_parts = {""};
ASSERT_EQ(test, StringJoin(parts, ";"));
ASSERT_EQ(StringSplit(test, ";"), parts);
ASSERT_EQ(empty, StringJoin(empty_parts, ";"));
ASSERT_EQ(StringSplit(empty, ";"), empty_parts);
}