From f9bf2c7e78e0a9b96d51a27039f28b3fb09b495f Mon Sep 17 00:00:00 2001 From: AnotherTest Date: Thu, 28 May 2020 00:51:43 +0430 Subject: [PATCH] AK: Add StringView::split_view() taking a StringView Since the task of splitting a string via another is pretty common, we might as well have this overload of split_view() as well. --- AK/StringView.cpp | 28 +++++++++++++++++++++++++++- AK/StringView.h | 1 + 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/AK/StringView.cpp b/AK/StringView.cpp index a8958426834..48df207656b 100644 --- a/AK/StringView.cpp +++ b/AK/StringView.cpp @@ -75,6 +75,32 @@ Vector StringView::split_view(const char separator, bool keep_empty) return v; } +Vector StringView::split_view(const StringView& separator, bool keep_empty) const +{ + ASSERT(!separator.is_empty()); + + if (is_empty()) + return {}; + + StringView view { *this }; + + Vector parts; + + auto maybe_separator_index = find_first_of(separator); + while (maybe_separator_index.has_value()) { + auto separator_index = maybe_separator_index.value(); + auto part_with_separator = view.substring_view(0, separator_index + separator.length()); + if (keep_empty || separator_index > 0) + parts.append(part_with_separator.substring_view(0, separator_index)); + view = view.substring_view_starting_after_substring(part_with_separator); + maybe_separator_index = view.find_first_of(separator); + } + if (keep_empty || !view.is_empty()) + parts.append(view); + + return parts; +} + Vector StringView::lines(bool consider_cr) const { if (is_empty()) @@ -244,7 +270,7 @@ Optional StringView::find_first_of(const StringView& view) const Optional StringView::find_last_of(char c) const { - for (size_t pos = m_length; --pos >0;) { + for (size_t pos = m_length; --pos > 0;) { if (m_characters[pos] == c) return pos; } diff --git a/AK/StringView.h b/AK/StringView.h index 9ba07735b27..f6a06afcc51 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -88,6 +88,7 @@ public: StringView substring_view(size_t start, size_t length) const; Vector split_view(char, bool keep_empty = false) const; + Vector split_view(const StringView&, bool keep_empty = false) const; // Create a Vector of StringViews split by line endings. As of CommonMark // 0.29, the spec defines a line ending as "a newline (U+000A), a carriage