C++ std::string Äquivalent zu Pythons lstrip

English Deutsch

In Python kannst du

lstrip_example.py
" test".lstrip()

in C++ ist der einfachste Weg jedoch die Verwendung der Boost String Algorithms-Bibliothek:

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);

_copy in trim_left_copy() bedeutet, dass der ursprüngliche String nicht verändert wird.

Vollständiges Beispiel:

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; // Prints 'test'
}

Falls du einen benutzerdefinierten Zeichensatz trimmen möchtest, verwende trim_left_copy_if() zusammen mit 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; // Prints 'Xtest'
}

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