Skip to content

Commit

Permalink
string_replace refactory
Browse files Browse the repository at this point in the history
  • Loading branch information
martysama0134 committed May 3, 2019
1 parent d8173e9 commit 05da192
Showing 1 changed file with 11 additions and 22 deletions.
33 changes: 11 additions & 22 deletions include/msl/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,6 @@ template <class T = std::vector<std::string>> std::string string_join(const T &
return str;
}

//! @brief string_replace replace all char instances of 'from' to 'to' into a new output string
inline std::string string_replace(std::string str, const char from, const char to)
{
for (auto & c : str)
{
if (c == from)
c = to;
}
return str;
}

//! @brief string_replace_in_place replace all char instances of 'from' to 'to' from the input string
inline void string_replace_in_place(std::string & str, const char from, const char to)
{
Expand All @@ -115,25 +104,18 @@ inline void string_replace_in_place(std::string & str, const char from, const ch
}
}

//! @brief string_replace replace all string instances of 'from' to 'to' into a new output string
inline std::string string_replace(std::string str, const std::string & from, const std::string & to)
//! @brief string_replace replace all char instances of 'from' to 'to' into a new output string
inline std::string string_replace(std::string str, const char from, const char to)
{
if (from.empty())
throw std::runtime_error("from is empty");
std::size_t pos = 0;
while ((pos = str.find(from, pos)) != std::string::npos)
{
str.replace(pos, from.length(), to);
pos += to.length();
}
string_replace_in_place(str, from, to);
return str;
}

//! @brief string_replace_in_place replace all string instances of 'from' to 'to' from the input string
inline void string_replace_in_place(std::string & str, const std::string & from, const std::string & to)
{
if (from.empty())
throw std::runtime_error("from is empty");
return;
std::size_t pos = 0;
while ((pos = str.find(from, pos)) != std::string::npos)
{
Expand All @@ -142,6 +124,13 @@ inline void string_replace_in_place(std::string & str, const std::string & from,
}
}

//! @brief string_replace replace all string instances of 'from' to 'to' into a new output string
inline std::string string_replace(std::string str, const std::string & from, const std::string & to)
{
string_replace_in_place(str, from, to);
return str;
}

//! @brief whitespaces returns a string containing the default ascii spaces
inline const char * whitespaces()
{
Expand Down

0 comments on commit 05da192

Please sign in to comment.