diff options
Diffstat (limited to 'base')
-rw-r--r-- | base/string_util.cc | 25 | ||||
-rw-r--r-- | base/string_util.h | 4 | ||||
-rw-r--r-- | base/string_util_unittest.cc | 18 |
3 files changed, 47 insertions, 0 deletions
diff --git a/base/string_util.cc b/base/string_util.cc index 63fec40..4ba8c4b 100644 --- a/base/string_util.cc +++ b/base/string_util.cc @@ -1140,6 +1140,31 @@ void SplitStringDontTrim(const std::string& str, SplitStringT(str, s, false, r); } +template<typename STR> +static STR JoinStringT(const std::vector<STR>& parts, + typename STR::value_type sep) { + if (parts.size() == 0) return STR(); + + STR result(parts[0]); + typename std::vector<STR>::const_iterator iter = parts.begin(); + ++iter; + + for (; iter != parts.end(); ++iter) { + result += sep; + result += *iter; + } + + return result; +} + +std::string JoinString(const std::vector<std::string>& parts, char sep) { + return JoinStringT(parts, sep); +} + +std::wstring JoinString(const std::vector<std::wstring>& parts, wchar_t sep) { + return JoinStringT(parts, sep); +} + void SplitStringAlongWhitespace(const std::wstring& str, std::vector<std::wstring>* result) { const size_t length = str.length(); diff --git a/base/string_util.h b/base/string_util.h index 28c5d35..6ee079a 100644 --- a/base/string_util.h +++ b/base/string_util.h @@ -494,6 +494,10 @@ void SplitStringDontTrim(const std::string& str, char s, std::vector<std::string>* r); +// Does the opposite of SplitString(). +std::wstring JoinString(const std::vector<std::wstring>& parts, wchar_t s); +std::string JoinString(const std::vector<std::string>& parts, char s); + // WARNING: this uses whitespace as defined by the HTML5 spec. If you need // a function similar to this but want to trim all types of whitespace, then // factor this out into a function that takes a string containing the characters diff --git a/base/string_util_unittest.cc b/base/string_util_unittest.cc index 7676f81..2b7634f 100644 --- a/base/string_util_unittest.cc +++ b/base/string_util_unittest.cc @@ -1299,6 +1299,24 @@ TEST(StringUtilTest, SplitString) { r.clear(); } +// Test for JoinString +TEST(StringUtilTest, JoinString) { + std::vector<std::string> in; + EXPECT_EQ("", JoinString(in, ',')); + + in.push_back("a"); + EXPECT_EQ("a", JoinString(in, ',')); + + in.push_back("b"); + in.push_back("c"); + EXPECT_EQ("a,b,c", JoinString(in, ',')); + + in.push_back(""); + EXPECT_EQ("a,b,c,", JoinString(in, ',')); + in.push_back(" "); + EXPECT_EQ("a|b|c|| ", JoinString(in, '|')); +} + TEST(StringUtilTest, StartsWith) { EXPECT_TRUE(StartsWithASCII("javascript:url", "javascript", true)); EXPECT_FALSE(StartsWithASCII("JavaScript:url", "javascript", true)); |