Skip to content

Commit

Permalink
De-duplicate replace_all and replace_all_copy
Browse files Browse the repository at this point in the history
Avoid a duplicated function body by having replace_all_copy simply call
replace_all on a local copy of the string and then return it.
  • Loading branch information
Matthew Mott committed Jan 30, 2021
1 parent 3a2cf88 commit e09b3c8
Showing 1 changed file with 6 additions and 15 deletions.
21 changes: 6 additions & 15 deletions libs/string/replace.h
Expand Up @@ -5,7 +5,7 @@
namespace string
{

/**
/**
* Replaces all occurrences of the given search string in the subject
* with the given replacement, in-place.
*/
Expand All @@ -23,24 +23,15 @@ inline void replace_all(std::string& subject, const std::string& search, const s
}

/**
* Replaces all occurrences of of the given search string with
* the given replacement and returns a new string instance
* Replaces all occurrences of of the given search string with
* the given replacement and returns a new string instance
* containing the result. The incoming subject is passed by value such
* that the original string is not altered.
*/
inline std::string replace_all_copy(std::string subject, const std::string& search, const std::string& replacement)
{
if (search.empty()) return subject; // nothing to do

std::size_t pos = 0;

while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replacement);
pos += replacement.length();
}

return subject;
replace_all(subject, search, replacement);
return subject;
}

/**
Expand All @@ -52,7 +43,7 @@ inline void replace_first(std::string& subject, const std::string& search, const
if (search.empty()) return; // nothing to do

std::size_t pos = subject.find(search);

if (pos != std::string::npos)
{
subject.replace(pos, search.length(), replacement);
Expand Down

0 comments on commit e09b3c8

Please sign in to comment.