diff options
author | Andreas Kling <kling@serenityos.org> | 2020-03-20 14:33:46 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-03-20 14:41:23 +0100 |
commit | 4eef3e5a09f6dcdddb654e05a77831ef27a3a537 (patch) | |
tree | 76676d2f2a4ee98a960411125ed52ce369793cdb /AK/StringBuilder.h | |
parent | 218f082226c16d44b765a23fe4d221e73cf96a1e (diff) | |
download | serenity-4eef3e5a09f6dcdddb654e05a77831ef27a3a537.zip |
AK: Add StringBuilder::join() for joining collections with a separator
This patch adds a generic StringBuilder::join(separator, collection):
Vector<String> strings = { "well", "hello", "friends" };
StringBuilder builder;
builder.join("+ ", strings);
builder.to_string(); // "well + hello + friends"
Diffstat (limited to 'AK/StringBuilder.h')
-rw-r--r-- | AK/StringBuilder.h | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/AK/StringBuilder.h b/AK/StringBuilder.h index 139fe3017a..fc627b230b 100644 --- a/AK/StringBuilder.h +++ b/AK/StringBuilder.h @@ -56,6 +56,19 @@ public: bool is_empty() const { return m_length == 0; } void trim(size_t count) { m_length -= count; } + template<class SeparatorType, class CollectionType> + void join(const SeparatorType& separator, const CollectionType& collection) + { + bool first = true; + for (auto& item : collection) { + if (first) + first = false; + else + append(separator); + append(item); + } + } + private: void will_append(size_t); |