From 042895317df85cb5035c011c9d5bda5a823c971d Mon Sep 17 00:00:00 2001 From: Conrad Pankoff Date: Tue, 4 Jun 2019 18:13:07 +1000 Subject: [PATCH] AK: Add AKString::split_limit to split strings with a limit This is a small change to the existing split() functionality to support the case of splitting a string and stopping at a certain number of tokens. This is useful for parsing e.g. key/value pairs, where the value may contain the delimiter you're splitting on. --- AK/AKString.h | 1 + AK/String.cpp | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/AK/AKString.h b/AK/AKString.h index 617bb6ab39..8f1119d80e 100644 --- a/AK/AKString.h +++ b/AK/AKString.h @@ -109,6 +109,7 @@ public: return m_impl->to_uppercase(); } + Vector split_limit(char separator, int limit) const; Vector split(char separator) const; String substring(int start, int length) const; diff --git a/AK/String.cpp b/AK/String.cpp index 8bfc787686..a7ac12fded 100644 --- a/AK/String.cpp +++ b/AK/String.cpp @@ -68,13 +68,18 @@ StringView String::substring_view(int start, int length) const } Vector String::split(const char separator) const +{ + return split_limit(separator, 0); +} + +Vector String::split_limit(const char separator, int limit) const { if (is_empty()) return {}; Vector v; ssize_t substart = 0; - for (ssize_t i = 0; i < length(); ++i) { + for (ssize_t i = 0; i < length() && (v.size() + 1) != limit; ++i) { char ch = characters()[i]; if (ch == separator) { ssize_t sublen = i - substart;