Skip to content

Commit 8126e7a

Browse files
committed
#41 - Implement method CppStringT::replace()
Added missing signature.
1 parent faaa942 commit 8126e7a

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

cpp-strings/cppstrings.h

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ namespace pcs // i.e. "pythonic c++ strings"
694694

695695

696696
//--- 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. */
697+
/** \brief Returns a copy of the string with all occurrences of substring old replaced by new. */
698698
inline CppStringT replace(const CppStringT& old, const CppStringT& new_) const noexcept
699699
{
700700
if (!this->contains(old))
@@ -707,12 +707,34 @@ namespace pcs // i.e. "pythonic c++ strings"
707707
res += this->substr(last_index, current_index - last_index) + new_;
708708
last_index = current_index;
709709
}
710+
710711
if (last_index != this->size())
711712
res += this->substr(last_index, this->size - last_index);
712713

713714
return res;
714715
}
715716

717+
/** \brief Returns a copy of the string with first count occurrences of substring old replaced by new. */
718+
inline CppStringT replace(const CppStringT& old, const CppStringT& new_, size_type count) const noexcept
719+
{
720+
if (!this->contains(old) || count == 0)
721+
return *this;
722+
723+
CppStringT res{};
724+
size_type last_index = 0;
725+
size_type current_index = 0;
726+
while (count > 0 && (current_index = this->find(old)) != CppStringT::npos) {
727+
res += this->substr(last_index, current_index - last_index) + new_;
728+
last_index = current_index;
729+
--count;
730+
}
731+
732+
if (last_index != this->size())
733+
res += this->substr(last_index, this->size - last_index);
734+
735+
return res;
736+
}
737+
716738

717739
//--- rfind() -----------------------------------------
718740
/** 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.

0 commit comments

Comments
 (0)