C++ std::string 等效于 Python 的 rstrip

在 Python 中你可以这样做

python_rstrip.py
"test ".rstrip()

而在 C++ 中最简单的方法是使用 Boost String Algorithms 库:

cpp_rstrip.cpp
#include <boost/algorithm/string/trim.hpp>

using namespace boost::algorithm;

string to_trim = "test ";
string trimmed = trim_right_copy(to_trim);

trim_right_copy() 中的 _copy 表示原始字符串不被修改。

完整示例:

cpp_rstrip_full.cpp
#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; // 打印 'test'
}

如果你想修剪自定义字符集,将 trim_right_copy_if()is_any_of() 一起使用:

cpp_rstrip_custom.cpp
#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; // 打印 'testX'
}

Check out similar posts by category: C/C++