string: add replaceInString

This commit is contained in:
Vaxry 2024-06-08 22:35:40 +02:00
parent 138408125c
commit f73a28ca03
4 changed files with 16 additions and 1 deletions

View file

@ -6,5 +6,6 @@ namespace Hyprutils {
// trims beginning and end of whitespace characters
std::string trim(const std::string& in);
bool isNumber(const std::string& str, bool allowfloat = false);
void replaceInString(std::string& string, const std::string& what, const std::string& to);
};
};

View file

@ -56,3 +56,13 @@ bool Hyprutils::String::isNumber(const std::string& str, bool allowfloat) {
return true;
}
void Hyprutils::String::replaceInString(std::string& string, const std::string& what, const std::string& to) {
if (string.empty())
return;
size_t pos = 0;
while ((pos = string.find(what, pos)) != std::string::npos) {
string.replace(pos, what.length(), to);
pos += to.length();
}
}

View file

@ -34,5 +34,9 @@ int main(int argc, char** argv, char** envp) {
EXPECT(list[0], "hello");
EXPECT(list[1], "world!");
std::string hello = "hello world!";
replaceInString(hello, "hello", "hi");
EXPECT(hello, "hi world!");
return ret;
}