AK: Add String::split_view(Function<bool(char)>)

This allows you to split around a custom separator, and enables
expressive code like this:

    string.split_view(is_ascii_space);
This commit is contained in:
Andreas Kling 2022-02-25 16:46:32 +01:00
parent 7ed6549c8b
commit dd7eb3d6d8
Notes: sideshowbarker 2024-07-17 18:16:54 +09:00
2 changed files with 9 additions and 2 deletions

View file

@ -7,6 +7,7 @@
#include <AK/ByteBuffer.h>
#include <AK/FlyString.h>
#include <AK/Format.h>
#include <AK/Function.h>
#include <AK/Memory.h>
#include <AK/StdLibExtras.h>
#include <AK/String.h>
@ -123,7 +124,7 @@ Vector<String> String::split_limit(char separator, size_t limit, bool keep_empty
return v;
}
Vector<StringView> String::split_view(const char separator, bool keep_empty) const
Vector<StringView> String::split_view(Function<bool(char)> separator, bool keep_empty) const
{
if (is_empty())
return {};
@ -132,7 +133,7 @@ Vector<StringView> String::split_view(const char separator, bool keep_empty) con
size_t substart = 0;
for (size_t i = 0; i < length(); ++i) {
char ch = characters()[i];
if (ch == separator) {
if (separator(ch)) {
size_t sublen = i - substart;
if (sublen != 0 || keep_empty)
v.append(substring_view(substart, sublen));
@ -145,6 +146,11 @@ Vector<StringView> String::split_view(const char separator, bool keep_empty) con
return v;
}
Vector<StringView> String::split_view(const char separator, bool keep_empty) const
{
return split_view([separator](char ch) { return ch == separator; }, keep_empty);
}
ByteBuffer String::to_byte_buffer() const
{
if (!m_impl)

View file

@ -150,6 +150,7 @@ public:
[[nodiscard]] Vector<String> split_limit(char separator, size_t limit, bool keep_empty = false) const;
[[nodiscard]] Vector<String> split(char separator, bool keep_empty = false) const;
[[nodiscard]] Vector<StringView> split_view(char separator, bool keep_empty = false) const;
[[nodiscard]] Vector<StringView> split_view(Function<bool(char)> separator, bool keep_empty = false) const;
[[nodiscard]] Optional<size_t> find(char needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); }
[[nodiscard]] Optional<size_t> find(StringView needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); }