add string replace function

This commit is contained in:
Jie 2025-01-06 14:51:33 +08:00
parent a2d35ba747
commit 061c574cce

View File

@ -2,10 +2,11 @@
#define TOOLKIT_H #define TOOLKIT_H
#include <charconv> #include <charconv>
#include <cstring>
#include <expected> #include <expected>
#include <type_traits> #include <type_traits>
#include <string_view>
#include <string> #include <string>
#include <cstdlib>
#include <ios> #include <ios>
//use for to_chars //use for to_chars
@ -44,6 +45,28 @@ namespace toolkit{
} }
return value; return value;
} }
template <typename T>
requires std::is_same_v<std::string, T> || std::is_same_v<const char*, T>
std::string replace_string(const std::string& str, T d, T e){
std::string result = str;
if(d == e){
return result;
}
size_t len = 0;
while(true){
auto pos = result.find_first_of(d);
if(pos == std::string::npos){
return result;
}
if constexpr(std::is_same_v<T, const char*>){
len = std::strlen(d);
}else{
len = d.length();
}
result = result.replace(pos, len ,e);
}
}
} }
#endif #endif