C++ std::string equivalent to Python's rstrip
In Python you can do
"test ".rstrip()
whereas in C++ the easiest way is to use the the Boost String Algorithms library:
#include <boost/algorithm/string/trim.hpp>
using namespace boost::algorithm;
string to_trim = "test ";
string trimmed = trim_right_copy(to_trim);
_copy
in trim_right_copy()
means that the original string is not modified.
Full example:
#include <iostream>
#include <string>
#include <boost/algorithm/string/trim.hpp>
using namespace std;
using namespace boost::algorithm;
int main() {
string to_trim = "test ";
string trimmed = trim_right_copy(to_trim);
cout << trimmed << endl; // Prints 'test'
}
In case you want to trim a custom set of characters, use trim_right_copy_if()
together with is_any_of()
:
#include <iostream>
#include <string>
#include <boost/algorithm/string/trim.hpp>
using namespace std;
using namespace boost::algorithm;
int main() {
string to_trim = "testXbbca";
string trimmed = trim_right_copy_if(to_trim, is_any_of("abc"));
cout << trimmed << endl; // Prints 'testX'
}