Skip to content

Commit 6d3729e

Browse files
committed
#45 - Implement method CppStringT::rpartition()
Completed.
1 parent 8126e7a commit 6d3729e

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

cpp-strings/cppstrings.h

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -695,7 +695,7 @@ namespace pcs // i.e. "pythonic c++ strings"
695695

696696
//--- replace() ---------------------------------------
697697
/** \brief Returns a copy of the string with all occurrences of substring old replaced by new. */
698-
inline CppStringT replace(const CppStringT& old, const CppStringT& new_) const noexcept
698+
CppStringT replace(const CppStringT& old, const CppStringT& new_) const noexcept
699699
{
700700
if (!this->contains(old))
701701
return *this;
@@ -715,7 +715,7 @@ namespace pcs // i.e. "pythonic c++ strings"
715715
}
716716

717717
/** \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
718+
CppStringT replace(const CppStringT& old, const CppStringT& new_, size_type count) const noexcept
719719
{
720720
if (!this->contains(old) || count == 0)
721721
return *this;
@@ -736,6 +736,27 @@ namespace pcs // i.e. "pythonic c++ strings"
736736
}
737737

738738

739+
//--- rpartition() -------------------------------------
740+
/** Split the string at the last occurrence of sep, and returns a 3-items vector containing the part before the separator, the separator itself, and the part after the separator.
741+
*
742+
* If the separator is not found, returns a 3-items vector
743+
* containing the string itself, followed by two empty strings.
744+
*/
745+
std::vector<CppStringT> rpartition(const CppStringT& sep) const noexcept
746+
{
747+
const size_type sep_index = rfind(sep);
748+
if (sep_index == CppStringT::npos) {
749+
const CppStringT empty{};
750+
return std::vector<CppStringT>({ *this, empty, empty });
751+
}
752+
else {
753+
const size_type third_index = sep_index + sep.size();
754+
const size_type third_size = this->size() - third_index + 1;
755+
return std::vector<CppStringT>({ this->substr(0, sep_index), sep, this->substr(third_index, third_size) });
756+
}
757+
}
758+
759+
739760
//--- rfind() -----------------------------------------
740761
/** 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.
741762
*

0 commit comments

Comments
 (0)