From 283a0e539ae4d5aa1051851d4a4801dbd3a365da Mon Sep 17 00:00:00 2001 From: Thilo Graf Date: Sun, 26 Feb 2023 01:57:48 +0100 Subject: [PATCH] system/helpers: Add new Parameter 'start_pos' to str_replace() This allows flexibility to specify a starting position from where to search for the first occurrence of the search string. By default, the position is set to 0 and the function will behave as before. However, when a position is provided, the function will replace only the first occurrence of the search string after that position. --- src/system/helpers.cpp | 25 +++++++++++++++++++------ src/system/helpers.h | 2 +- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/system/helpers.cpp b/src/system/helpers.cpp index 12fa6b4a6..cd05bb502 100644 --- a/src/system/helpers.cpp +++ b/src/system/helpers.cpp @@ -690,17 +690,30 @@ time_t toEpoch(std::string &date) } -std::string& str_replace(const std::string &search, const std::string &replace, std::string &text) +/** + * Replaces all occurrences of a substring with another string in a given text, + * starting from a specified position. + * + * @param search The substring to search for. + * @param replace The string to replace the occurrences of `search` with. + * @param text The text to perform the replacement on. + * @param start_pos The position to start searching for `search` in `text`. + * Default value is 0. + * + * @return The modified text after all replacements have been made. + */ +std::string &str_replace(const std::string &search, const std::string &replace, std::string &text, size_t start_pos) { if (search.empty() || text.empty()) return text; size_t searchLen = search.length(); - while (1) { - size_t pos = text.find(search); - if (pos == std::string::npos) - break; - text.replace(pos, searchLen, replace); + size_t startPos = text.find(search, start_pos); + + while (startPos != std::string::npos) + { + text.replace(startPos, searchLen, replace); + startPos = text.find(search, startPos + replace.length()); } return text; } diff --git a/src/system/helpers.h b/src/system/helpers.h index d7cf22bfc..d7de9661b 100644 --- a/src/system/helpers.h +++ b/src/system/helpers.h @@ -82,7 +82,7 @@ std::string strftime(const char *format, const struct tm *tm); std::string strftime(const char *format, time_t when, bool gm = false); time_t toEpoch(std::string &date); const char *cstr_replace(const char *search, const char *replace, const char *text); -std::string& str_replace(const std::string &search, const std::string &replace, std::string &text); +std::string& str_replace(const std::string &search, const std::string &replace, std::string &text, size_t start_pos = 0); std::string& htmlEntityDecode(std::string& text); const char* neutrinoMode_to_string(int mode);