Skip to content

Commit 5a0840a

Browse files
committed
Add removeprefix and removesuffix to pystring
Add removeprefix and removesuffix to pystring. Python 3.9 added removeprefix and removesuffix methods to Pythons string class. Add them to pystring to match the interfaces.
1 parent 281419d commit 5a0840a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

pystring.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,6 +1071,31 @@ const std::string colon = ":";
10711071
return os.str();
10721072
}
10731073

1074+
//////////////////////////////////////////////////////////////////////////////////////////////
1075+
///
1076+
///
1077+
std::string removeprefix( const std::string & str, const std::string & prefix )
1078+
{
1079+
if (pystring::startswith(str, prefix))
1080+
{
1081+
return str.substr(prefix.length());
1082+
}
1083+
1084+
return str;
1085+
}
1086+
1087+
//////////////////////////////////////////////////////////////////////////////////////////////
1088+
///
1089+
///
1090+
std::string removesuffix( const std::string & str, const std::string & suffix )
1091+
{
1092+
if (pystring::endswith(str, suffix))
1093+
{
1094+
return str.substr(0, str.length() - suffix.length());
1095+
}
1096+
1097+
return str;
1098+
}
10741099

10751100

10761101
namespace os

pystring.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,18 @@ namespace pystring
179179
///
180180
void partition( const std::string & str, const std::string & sep, std::vector< std::string > & result );
181181

182+
//////////////////////////////////////////////////////////////////////////////////////////////
183+
/// @brief If str starts with prefix return a copy of the string with prefix at the start
184+
/// removed otherwise return an unmodified copy of the string.
185+
///
186+
std::string removeprefix( const std::string & str, const std::string & prefix );
187+
188+
//////////////////////////////////////////////////////////////////////////////////////////////
189+
/// @brief If str ends with suffix return a copy of the string with suffix at the end removed
190+
/// otherwise return an unmodified copy of the string.
191+
///
192+
std::string removesuffix( const std::string & str, const std::string & suffix );
193+
182194
//////////////////////////////////////////////////////////////////////////////////////////////
183195
/// @brief Return a copy of the string with all occurrences of substring old replaced by new. If
184196
/// the optional argument count is given, only the first count occurrences are replaced.

0 commit comments

Comments
 (0)