Skip to content

Commit

Permalink
string: add replaceInString
Browse files Browse the repository at this point in the history
  • Loading branch information
vaxerski committed Jun 8, 2024
1 parent 1384081 commit f73a28c
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions include/hyprutils/string/String.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
};
10 changes: 10 additions & 0 deletions src/string/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
2 changes: 1 addition & 1 deletion tests/shared.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ namespace Colors {
ret = 1; \
} else { \
std::cout << Colors::GREEN << "Passed " << Colors::RESET << #expr << ". Got " << val << "\n"; \
}
}
4 changes: 4 additions & 0 deletions tests/string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit f73a28c

Please sign in to comment.