From bd831df8608d03c9db608b2103972681d2db2775 Mon Sep 17 00:00:00 2001 From: Fabian Peller-Konrad <fabian.peller-konrad@kit.edu> Date: Tue, 1 Mar 2022 09:32:55 +0100 Subject: [PATCH] added string count method --- SimoxUtility/algorithm/string/string_tools.cpp | 14 ++++++++++++++ SimoxUtility/algorithm/string/string_tools.h | 10 ++++++++++ 2 files changed, 24 insertions(+) diff --git a/SimoxUtility/algorithm/string/string_tools.cpp b/SimoxUtility/algorithm/string/string_tools.cpp index 6e2de9244..d58391f0a 100644 --- a/SimoxUtility/algorithm/string/string_tools.cpp +++ b/SimoxUtility/algorithm/string/string_tools.cpp @@ -176,6 +176,20 @@ bool alg::contains(const std::string& haystack, const std::string& needle) return boost::algorithm::contains(haystack, needle); } +unsigned long alg::count(const std::string& input, const std::string& search) +{ + auto start = 0U; + auto end = input.find(search); + unsigned long num = 0; + while (end != std::string::npos) + { + num++; + start = end + search.length(); + end = input.find(search, start); + } + return num; +} + std::string alg::remove_prefix(const std::string& string, const std::string& prefix) { diff --git a/SimoxUtility/algorithm/string/string_tools.h b/SimoxUtility/algorithm/string/string_tools.h index 73e2ba7fe..656b721fd 100644 --- a/SimoxUtility/algorithm/string/string_tools.h +++ b/SimoxUtility/algorithm/string/string_tools.h @@ -100,6 +100,16 @@ namespace simox::alg return string.find(character) != std::string::npos; } + unsigned long count(const std::string& input, const std::string& search); + inline unsigned long count(const std::string& input, const char* search) + { + return count(input, std::string(search)); + } + inline unsigned long count(const std::string& input, const char search) + { + return count(input, std::to_string(search)); + } + /** * @brief If `string` begins with `prefix`, return `string` without the -- GitLab