From f73a28ca03602376ae41970e7b683baf8a600848 Mon Sep 17 00:00:00 2001 From: Vaxry Date: Sat, 8 Jun 2024 22:35:40 +0200 Subject: [PATCH] string: add replaceInString --- include/hyprutils/string/String.hpp | 1 + src/string/String.cpp | 10 ++++++++++ tests/shared.hpp | 2 +- tests/string.cpp | 4 ++++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/include/hyprutils/string/String.hpp b/include/hyprutils/string/String.hpp index 933e727..6490d07 100644 --- a/include/hyprutils/string/String.hpp +++ b/include/hyprutils/string/String.hpp @@ -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); }; }; \ No newline at end of file diff --git a/src/string/String.cpp b/src/string/String.cpp index 24bb14f..87564c8 100644 --- a/src/string/String.cpp +++ b/src/string/String.cpp @@ -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(); + } +} diff --git a/tests/shared.hpp b/tests/shared.hpp index b267426..ce3d771 100644 --- a/tests/shared.hpp +++ b/tests/shared.hpp @@ -17,4 +17,4 @@ namespace Colors { ret = 1; \ } else { \ std::cout << Colors::GREEN << "Passed " << Colors::RESET << #expr << ". Got " << val << "\n"; \ - } \ No newline at end of file + } diff --git a/tests/string.cpp b/tests/string.cpp index 64bcaf6..813cfe6 100644 --- a/tests/string.cpp +++ b/tests/string.cpp @@ -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; } \ No newline at end of file