summaryrefslogtreecommitdiff
path: root/AK/String.cpp
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2022-02-25 16:46:32 +0100
committerAndreas Kling <kling@serenityos.org>2022-02-25 19:38:31 +0100
commitdd7eb3d6d8f61549fbd2c3e80cf0b08757c4d3dd (patch)
tree9c552c71b44d04df4f828facfe3253c45f48bf54 /AK/String.cpp
parent7ed6549c8b1dbf2e0ba941578c8bb1e723769c3f (diff)
downloadserenity-dd7eb3d6d8f61549fbd2c3e80cf0b08757c4d3dd.zip
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);
Diffstat (limited to 'AK/String.cpp')
-rw-r--r--AK/String.cpp10
1 files changed, 8 insertions, 2 deletions
diff --git a/AK/String.cpp b/AK/String.cpp
index 7eeb97cc8e..1e18bca9a2 100644
--- a/AK/String.cpp
+++ b/AK/String.cpp
@@ -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)