diff --git a/paddle/fluid/string/string_helper.h b/paddle/fluid/string/string_helper.h index 4f1aee7c7ed17fd454e1965b7bc53a7d27a44a3f..c52b7a99a777a7eac714e6533101368e35844c21 100644 --- a/paddle/fluid/string/string_helper.h +++ b/paddle/fluid/string/string_helper.h @@ -193,6 +193,22 @@ std::string join_strings(const Container& strs, const std::string& delim) { return str; } +template +std::string join_strings(const Container& strs, DelimT&& delim, + ConvertFunc&& func) { + std::stringstream ss; + size_t i = 0; + for (const auto& elem : strs) { + if (i > 0) { + ss << delim; + } + ss << func(elem); + ++i; + } + + return ss.str(); +} + // A helper class for reading lines from file. A line buffer is maintained. It // doesn't need to know the maximum possible length of a line. diff --git a/paddle/fluid/string/string_helper_test.cc b/paddle/fluid/string/string_helper_test.cc index 4796bf7507aba7f8afac06dc33f08c7025b33d4b..67456e16a93b67f39d86c5751e35148be7020f61 100644 --- a/paddle/fluid/string/string_helper_test.cc +++ b/paddle/fluid/string/string_helper_test.cc @@ -56,3 +56,10 @@ TEST(StringHelper, JoinStrings) { result = paddle::string::join_strings(v, " new "); EXPECT_EQ(result, "hello new world"); } + +TEST(StringHelper, JoinStringsWithConversion) { + std::vector v = {2, 3}; + auto result = + paddle::string::join_strings(v, ",", [](int x) { return x * x; }); + EXPECT_EQ(result, "4,9"); +}