Skip to content

Commit

Permalink
Implement joining iterator ranges into a string
Browse files Browse the repository at this point in the history
  • Loading branch information
RainerKuemmerle committed Aug 13, 2024
1 parent 0068c61 commit 5e816df
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
26 changes: 26 additions & 0 deletions g2o/stuff/string_tools.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
#ifndef G2O_STRING_TOOLS_H
#define G2O_STRING_TOOLS_H

#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
Expand Down Expand Up @@ -115,6 +117,30 @@ G2O_STUFF_API std::string strExpandFilename(const std::string& filename);
G2O_STUFF_API std::vector<std::string> strSplit(const std::string& s,
const std::string& delim);

/**
* @brief Join into a string using a delimeter
*
* @tparam Iterator
* @tparam std::iterator_traits<Iterator>::value_type
* @param b begin of the range for output
* @param e end of the range for output
* @param delimiter will be inserted in between elements
* @return std::string joined string
*/
template <typename Iterator,
typename Value = typename std::iterator_traits<Iterator>::value_type>
std::string strJoin(Iterator b, Iterator e, const std::string& delimiter = "") {
if (b == e) return "";
std::ostringstream os;
std::copy(b, std::prev(e),
std::ostream_iterator<Value>(os, delimiter.c_str()));
b = std::prev(e);
if (b != e) {
os << *b;
}
return os.str();
}

/**
* read a line from is into currentLine.
* @return the number of characters read into currentLine (excluding newline),
Expand Down
8 changes: 8 additions & 0 deletions unit_test/stuff/string_tools_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ TEST(Stuff, StrSplit) {
ASSERT_EQ(std::to_string(i + 1), tokens[i]);
}

TEST(Stuff, StrJoin) {
std::vector<int> int_data = {1, 2, 3};
EXPECT_EQ("123", g2o::strJoin(int_data.begin(), int_data.end()));
EXPECT_EQ("1", g2o::strJoin(int_data.begin(), std::next(int_data.begin())));
EXPECT_EQ("", g2o::strJoin(int_data.begin(), int_data.begin()));
EXPECT_EQ("1, 2, 3", g2o::strJoin(int_data.begin(), int_data.end(), ", "));
}

TEST(Stuff, StrStartsWith) {
ASSERT_FALSE(g2o::strStartsWith("Hello World!", "World!"));
ASSERT_TRUE(g2o::strStartsWith("Hello World!", "Hello"));
Expand Down

0 comments on commit 5e816df

Please sign in to comment.