[base] strings::JoinAny is added + test

This commit is contained in:
Arsentiy Milchakov 2019-11-18 12:39:18 +03:00 committed by Maksim Andrianov
parent 712df5f52c
commit c124c9032e
2 changed files with 72 additions and 0 deletions

View file

@ -6,6 +6,7 @@
#include <fstream>
#include <functional>
#include <iomanip>
#include <list>
#include <map>
#include <string>
#include <unordered_map>
@ -841,3 +842,45 @@ UNIT_TEST(UniString_Replace)
TEST_EQUAL(testString, ToUtf8(uniStr), ());
}
}
UNIT_TEST(Strings_JoinAny)
{
{
std::vector<int> testSequence{1, 2, 3};
std::string expected{"1,2,3"};
TEST_EQUAL(expected, strings::JoinAny(testSequence), ());
}
{
std::list<std::string> testSequence{"1", "2", "3"};
std::string expected{"1,2,3"};
TEST_EQUAL(expected, strings::JoinAny(testSequence), ());
}
{
std::vector<char> testSequence{'1', '2', '3'};
std::string expected{"1,2,3"};
TEST_EQUAL(expected, strings::JoinAny(testSequence), ());
}
{
std::list<std::string> testSequence{"1", "2", "3"};
std::string expected{"1xyz2xyz3"};
TEST_EQUAL(expected, strings::JoinAny(testSequence, "xyz"), ());
}
{
std::vector<std::string> testSequence{"name:X", "name:Y", "name:Z"};
std::string expected{"X; Y; Z"};
TEST_EQUAL(expected,
strings::JoinAny(testSequence, "; ",
[](auto const & line) {
auto const pos = line.find(":");
return line.substr(pos + 1);
}),
());
}
{
std::map<int, std::string> testSequence{{1, "maps"}, {2, "."}, {3, "me"}};
std::string expected{"maps.me"};
TEST_EQUAL(expected,
strings::JoinAny(testSequence, "",
[](auto const & item) { return item.second; }), ());
}
}

View file

@ -568,6 +568,35 @@ typename Container::value_type JoinStrings(Container const & container, Delimite
return JoinStrings(begin(container), end(container), delimiter);
}
template <typename Iterator, typename Delimiter, typename Converter>
std::string JoinAny(Iterator first, Iterator last, Delimiter const & delimiter,
Converter const & converter)
{
if (first == last)
return {};
std::string result(converter(*first));
++first;
for (; first != last; ++first)
{
result += delimiter;
result += converter(*first);
}
return result;
}
template <typename Container, typename Delimiter = char const>
std::string JoinAny(Container const & container,
Delimiter const & delimiter = ',',
std::function<
std::string (typename Container::value_type const & v)> const & converter =
[](typename Container::value_type const & item)
{ return to_string(item); })
{
return JoinAny(std::cbegin(container), std::cend(container), delimiter, converter);
}
template <typename Fn>
void ForEachMatched(std::string const & s, std::regex const & regex, Fn && fn)
{