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

在 Python 中你可以这样做

lstrip_example.py
" test".lstrip()

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

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

using namespace boost::algorithm;

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

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

完整示例:

trim_left_example.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_left_copy(to_trim);
    cout << trimmed << endl; // 打印 'test'
}

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

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

using namespace std;
using namespace boost::algorithm;

int main() {
    string to_trim = "bbcaXtest";
    string trimmed = trim_left_copy_if(to_trim, is_any_of("abc"));
    cout << trimmed << endl; // 打印 'Xtest'
}

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