diff --git a/headers/os/support/String.h b/headers/os/support/String.h index a487a040e3..005fcd219a 100644 --- a/headers/os/support/String.h +++ b/headers/os/support/String.h @@ -11,6 +11,7 @@ #include +class BStringList; class BStringRef; @@ -66,6 +67,9 @@ public: bool CopyCharsInto(char* into, int32* intoLength, int32 fromCharOffset, int32 charCount) const; + bool Split(const char* separator, bool noEmptyStrings, + BStringList& _list) const; + // Appending BString& operator+=(const BString& string); BString& operator+=(const char* string); diff --git a/src/kits/support/String.cpp b/src/kits/support/String.cpp index e1b7a8e0b4..7bc0751d56 100644 --- a/src/kits/support/String.cpp +++ b/src/kits/support/String.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -510,6 +511,42 @@ BString::CopyCharsInto(char* into, int32* intoLength, int32 fromCharOffset, } +bool +BString::Split(const char* separator, bool noEmptyStrings, + BStringList& _list) const +{ + int32 separatorLength = strlen(separator); + int32 length = Length(); + if (separatorLength == 0 || length == 0 || separatorLength > length) { + if (length == 0 && noEmptyStrings) + return true; + return _list.Add(*this); + } + + int32 index = 0; + for (;;) { + int32 endIndex = index < length ? FindFirst(separator, index) : length; + if (endIndex < 0) + endIndex = length; + + if (endIndex > index || !noEmptyStrings) { + BString toAppend(String() + index, endIndex - index); + if (toAppend.Length() != endIndex - index + || _list.Add(toAppend)) { + return false; + } + } + + if (endIndex == length) + break; + + index = endIndex + 1; + } + + return true; +} + + // #pragma mark - Appending