Skip to content

Commit

Permalink
[core] Counterpart of Pythons str.join function in C++
Browse files Browse the repository at this point in the history
This complements the existing `ROOT::Split()` function.
  • Loading branch information
ferdymercury authored Nov 13, 2023
1 parent 04ec405 commit 52bf59d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/foundation/inc/ROOT/StringUtils.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,28 @@

#include <string>
#include <vector>
#include <numeric>

namespace ROOT {

std::vector<std::string> Split(std::string_view str, std::string_view delims, bool skipEmpty = false);

/**
* \brief Concatenate a list of strings with a separator
* \tparm Any container of strings (vector, initializer_list, ...)
* \param[in] sep Separator inbetween the strings.
* \param[in] strings container of strings
* \return the sep-delimited concatenation of strings
*/
template <class StringCollection_t>
std::string Join(const std::string &sep, StringCollection_t &&strings)
{
if (strings.empty())
return "";
return std::accumulate(std::next(std::begin(strings)), std::end(strings), strings[0],
[&sep](auto const &a, auto const &b) { return a + sep + b; });
}

} // namespace ROOT

#endif
20 changes: 20 additions & 0 deletions core/foundation/test/testStringUtils.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,23 @@ TEST(StringUtils, Split)
test(",,a", {"", "", "a"}, false);
test("", {""}, false);
}

TEST(StringUtils, Join)
{
// Test that ROOT::Join behaves like str.join from Python.

auto test = [](const std::string &ref, const std::string &sep, const std::vector<std::string> &strings) {
auto out = ROOT::Join(sep, strings);
EXPECT_EQ(out, ref) << "ROOT::Join gave wrong result.";
};
test("apple,orange,banana", ",", {"apple", "orange", "banana"});
test("apple.orange.banana", ".", {"apple", "orange", "banana"});
test("apple::orange::banana", "::", {"apple", "orange", "banana"});
test("appleorangebanana", "", {"apple", "orange", "banana"});
test("apple,,banana", ",", {"apple", "", "banana"});
test("apple", ",", {"apple"});
test("", ",", {""});
test("", "", {""});
test("", "", {});
test("", ";;", {""});
}

0 comments on commit 52bf59d

Please sign in to comment.