summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorConrad Pankoff <deoxxa@fknsrs.biz>2019-06-04 18:13:07 +1000
committerAndreas Kling <awesomekling@gmail.com>2019-06-04 10:16:45 +0200
commit042895317df85cb5035c011c9d5bda5a823c971d (patch)
tree302d6a4c969107731968b2826fbf2fe6ea9d6ab6
parentccc6e69a294edacf7bec77cb2c2640ada7fe1f77 (diff)
downloadserenity-042895317df85cb5035c011c9d5bda5a823c971d.zip
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.
-rw-r--r--AK/AKString.h1
-rw-r--r--AK/String.cpp7
2 files changed, 7 insertions, 1 deletions
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<String> split_limit(char separator, int limit) const;
Vector<String> 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
@@ -69,12 +69,17 @@ StringView String::substring_view(int start, int length) const
Vector<String> String::split(const char separator) const
{
+ return split_limit(separator, 0);
+}
+
+Vector<String> String::split_limit(const char separator, int limit) const
+{
if (is_empty())
return {};
Vector<String> 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;