toolkit/include/stringconv.h
2025-03-06 13:30:01 +08:00

67 lines
1.7 KiB
C++

#ifndef STRINGCONV_H
#define STRINGCONV_H
#include <type_traits>
#include <string>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <ranges>
namespace ranges = std::ranges;
namespace views = std::ranges::views;
constexpr size_t buffer_size = 32;
namespace string{
template <typename T>
requires std::is_same_v<std::string, T> || std::is_same_v<const char *, T>
inline 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(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);
}
}
template <typename T = std::string>
requires std::is_same_v<T, std::string> ||
std::is_same_v<T, std::string_view>
inline std::vector<T> split(T str, T d)
{
auto v = views::split(str, d) | views::transform([](auto word)
{ return T(word.begin(), word.end()); });
return std::vector<T>(v.begin(), v.end());
}
template<typename T>
requires std::is_same_v<T, double> || std::is_same_v<T, float>
double round(T value, int c){
auto temp = 1;
for(int i=0;i<c;i++){
temp=temp*10;
}
return std::round(value*temp)/temp;
}
}
#endif