diff --git a/pystring.cpp b/pystring.cpp index dfc5e09..765e76a 100644 --- a/pystring.cpp +++ b/pystring.cpp @@ -1043,6 +1043,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 35b6416..12dee5e 100644 --- a/pystring.h +++ b/pystring.h @@ -157,6 +157,18 @@ namespace pystring return 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 110c673..ed702de 100644 --- a/test.cpp +++ b/test.cpp @@ -98,6 +98,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");