Skip to content

Commit

Permalink
New replace_all for replacing strings
Browse files Browse the repository at this point in the history
  • Loading branch information
kraxarn committed Aug 14, 2021
1 parent d005017 commit 5fd6a60
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/include/lib/strings.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,16 @@ namespace lib
static auto replace_all(const std::string &str,
char old_val, char new_val) -> std::string;

/**
* Replace all occurrences of a string in another string
* @param str String to replace in
* @param old_val Old string
* @param new_val New string
* @return New string with string replaced
*/
static auto replace_all(const std::string &str,
const std::string &old_val, const std::string &new_val) -> std::string;

private:
/**
* Trim beginning of string
Expand Down
15 changes: 15 additions & 0 deletions lib/src/strings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,18 @@ auto strings::replace_all(const std::string &str, char old_val, char new_val) ->
std::replace(val.begin(), val.end(), old_val, new_val);
return val;
}

auto strings::replace_all(const std::string &str, const std::string &old_val,
const std::string &new_val) -> std::string
{
std::string val = str;
size_t pos = val.find(old_val);

while (pos != std::string::npos)
{
val.replace(pos, old_val.size(), new_val);
pos = val.find(old_val, pos + old_val.size());
}

return val;
}

0 comments on commit 5fd6a60

Please sign in to comment.