From 5378b913a69f0f8f527eff3d77862cb29df3476e Mon Sep 17 00:00:00 2001 From: Attila Molnar Date: Mon, 22 Aug 2016 17:10:41 +0200 Subject: Add stdalgo::string::replace() and replace_all() --- include/stdalgo.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/include/stdalgo.h b/include/stdalgo.h index 12ec76275..f4465963a 100644 --- a/include/stdalgo.h +++ b/include/stdalgo.h @@ -94,6 +94,41 @@ namespace stdalgo { return (!strcasecmp(tocstr(str1), tocstr(str2))); } + + /** Replace first occurrence of a substring ('target') in a string ('str') with another string ('replacement'). + * @param str String to perform replacement in + * @param target String to replace + * @param replacement String to put in place of 'target' + * @return True if 'target' was replaced with 'replacement', false if it was not found in 'str'. + */ + template + inline bool replace(std::basic_string& str, const std::basic_string& target, const std::basic_string& replacement) + { + const typename std::basic_string::size_type p = str.find(target); + if (p == std::basic_string::npos) + return false; + str.replace(p, target.size(), replacement); + return true; + } + + /** Replace all occurrences of a string ('target') in a string ('str') with another string ('replacement'). + * @param str String to perform replacement in + * @param target String to replace + * @param replacement String to put in place of 'target' + */ + template + inline void replace_all(std::basic_string& str, const std::basic_string& target, const std::basic_string& replacement) + { + if (target.empty()) + return; + + typename std::basic_string::size_type p = 0; + while ((p = str.find(target, p)) != std::basic_string::npos) + { + str.replace(p, target.size(), replacement); + p += replacement.size(); + } + } } /** -- cgit v1.2.3