Skip to content

Commit f788380

Browse files
committed
#41 - Implement method CppStringT::replace()
Completed.
1 parent de3e8e0 commit f788380

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

cpp-strings/cppstrings.h

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,27 @@ namespace pcs // i.e. "pythonic c++ strings"
693693
}
694694

695695

696+
//--- replace() ---------------------------------------
697+
/** \brief Returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. */
698+
inline CppStringT replace(const CppStringT& old, const CppStringT& new_) const noexcept
699+
{
700+
if (!this->contains(old))
701+
return *this;
702+
703+
CppStringT res{};
704+
size_type last_index = 0;
705+
size_type current_index = 0;
706+
while ((current_index = this->find(old)) != CppStringT::npos) {
707+
res += this->substr(last_index, current_index - last_index) + new_;
708+
last_index = current_index;
709+
}
710+
if (last_index != this->size())
711+
res += this->substr(last_index, this->size - last_index);
712+
713+
return res;
714+
}
715+
716+
696717
//--- rfind() -----------------------------------------
697718
/** Returns the highest index in the string where substring sub is found within the slice str[start:end], or -1 (i.e. 'npos') if sub is not found.
698719
*

0 commit comments

Comments
 (0)