From 3556c27d2d1bcd99d361df757f4b52d12282c784 Mon Sep 17 00:00:00 2001 From: Dan Klishch Date: Mon, 14 Aug 2023 21:55:36 -0400 Subject: [PATCH] AK: Add StringView::count(char) --- AK/StringUtils.cpp | 10 ++++++++++ AK/StringUtils.h | 1 + AK/StringView.h | 5 +++++ 3 files changed, 16 insertions(+) diff --git a/AK/StringUtils.cpp b/AK/StringUtils.cpp index fd242adf00..7bac50a8a0 100644 --- a/AK/StringUtils.cpp +++ b/AK/StringUtils.cpp @@ -593,6 +593,16 @@ size_t count(StringView str, StringView needle) return count; } +size_t count(StringView str, char needle) +{ + size_t count = 0; + for (size_t i = 0; i < str.length(); ++i) { + if (str[i] == needle) + count++; + } + return count; +} + } } diff --git a/AK/StringUtils.h b/AK/StringUtils.h index 591340b993..190bb3293d 100644 --- a/AK/StringUtils.h +++ b/AK/StringUtils.h @@ -107,6 +107,7 @@ DeprecatedString replace(StringView, StringView needle, StringView replacement, ErrorOr replace(String const&, StringView needle, StringView replacement, ReplaceMode); size_t count(StringView, StringView needle); +size_t count(StringView, char needle); } diff --git a/AK/StringView.h b/AK/StringView.h index 2ea870c551..fb68c0e101 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -330,6 +330,11 @@ public: return StringUtils::count(*this, needle); } + [[nodiscard]] size_t count(char needle) const + { + return StringUtils::count(*this, needle); + } + template [[nodiscard]] ALWAYS_INLINE constexpr bool is_one_of(Ts&&... strings) const {