X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=include%2Fstdalgo.h;h=f4465963a65f5bd0884831d647ca5f4ffea65799;hb=8920cb1b9f2c0b50ca326e5fa0646db40acccdbc;hp=12ec76275f8e979fc7b4c993b9f90ed063728930;hpb=90ea1b01b78a94486b8142808c06aacff543ca64;p=user%2Fhenk%2Fcode%2Finspircd.git 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(); + } + } } /**