diff --git a/pystring.cpp b/pystring.cpp index e17aa68..ef3f98d 100644 --- a/pystring.cpp +++ b/pystring.cpp @@ -1071,6 +1071,31 @@ const std::string colon = ":"; return os.str(); } + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string removeprefix( const std::string & str, const std::string & prefix ) + { + if (pystring::startswith(str, prefix)) + { + return str.substr(prefix.length()); + } + + return str; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string removesuffix( const std::string & str, const std::string & suffix ) + { + if (pystring::endswith(str, suffix)) + { + return str.substr(0, str.length() - suffix.length()); + } + + return str; + } namespace os diff --git a/pystring.h b/pystring.h index 45ffd9a..fad270c 100644 --- a/pystring.h +++ b/pystring.h @@ -179,6 +179,18 @@ namespace pystring /// void partition( const std::string & str, const std::string & sep, std::vector< std::string > & result ); + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief If str starts with prefix return a copy of the string with prefix at the start + /// removed otherwise return an unmodified copy of the string. + /// + std::string removeprefix( const std::string & str, const std::string & prefix ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief If str ends with suffix return a copy of the string with suffix at the end removed + /// otherwise return an unmodified copy of the string. + /// + std::string removesuffix( const std::string & str, const std::string & suffix ); + ////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Return 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. diff --git a/test.cpp b/test.cpp index dea2dbe..ea3628a 100644 --- a/test.cpp +++ b/test.cpp @@ -94,6 +94,18 @@ PYSTRING_ADD_TEST(pystring, rfind) PYSTRING_CHECK_EQUAL(pystring::rfind("abcabcabc", "abc", 6, 8), -1); } +PYSTRING_ADD_TEST(pystring, removeprefix) +{ + PYSTRING_CHECK_EQUAL(pystring::removeprefix("abcdef", "abc"), "def"); + PYSTRING_CHECK_EQUAL(pystring::removeprefix("abcdef", "bcd"), "abcdef"); +} + +PYSTRING_ADD_TEST(pystring, removesuffix) +{ + PYSTRING_CHECK_EQUAL(pystring::removesuffix("abcdef", "def"), "abc"); + PYSTRING_CHECK_EQUAL(pystring::removesuffix("abcdef", "cde"), "abcdef"); +} + PYSTRING_ADD_TEST(pystring, replace) { PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "foo", "bar"), "abcdef");