diff --git a/headers/os/support/StringList.h b/headers/os/support/StringList.h index dba5edf70a..2c973a1623 100644 --- a/headers/os/support/StringList.h +++ b/headers/os/support/StringList.h @@ -50,6 +50,8 @@ public: int32 CountStrings() const; bool IsEmpty() const; + BString Join(const char* separator, int32 length = -1); + // Iteration void DoForEach(bool (*func)(const BString& string)); void DoForEach(bool (*func)(const BString& string, @@ -63,6 +65,8 @@ private: void _IncrementRefCounts() const; void _DecrementRefCounts() const; + BString _Join(const char* separator, int32 length); + private: BList fStrings; }; diff --git a/src/kits/support/StringList.cpp b/src/kits/support/StringList.cpp index 9e0dc8ce22..588cbc0499 100644 --- a/src/kits/support/StringList.cpp +++ b/src/kits/support/StringList.cpp @@ -260,6 +260,14 @@ BStringList::IsEmpty() const } +BString +BStringList::Join(const char* separator, int32 length) +{ + return _Join(separator, + length >= 0 ? strnlen(separator, length) : strlen(separator)); +} + + void BStringList::DoForEach(bool (*func)(const BString& string)) { @@ -328,3 +336,39 @@ BStringList::_DecrementRefCounts() const for (int32 i = 0; i < count; i++) BString::Private::DecrementDataRefCount((char*)fStrings.ItemAt(i)); } + + +BString +BStringList::_Join(const char* separator, int32 length) +{ + // handle simple cases (0 or 1 element) + int32 count = CountStrings(); + if (count == 0) + return BString(); + if (count == 1) + return StringAt(0); + + // determine the total length + int32 totalLength = length * (count - 1); + for (int32 i = 0; i < count; i++) + totalLength += StringAt(i).Length(); + + // compose the result string + BString result; + char* buffer = result.LockBuffer(totalLength); + if (buffer == NULL) + return result; + + for (int32 i = 0; i < count; i++) { + if (i > 0 && length > 0) { + memcpy(buffer, separator, length); + buffer += length; + } + + BString string = StringAt(i); + memcpy(buffer, string.String(), string.Length()); + buffer += string.Length(); + } + + return result.UnlockBuffer(totalLength); +}