Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách trim (xóa khoảng trắng) std::string trong C++


C++ chuẩn chưa có trim. Dùng Boost.StringAlgo: boost::trim_left, boost::trim_right, boost::trim.

Ví dụ

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;

int main() {
    string s = "  Hello World  ";
    cout << "(" << s << ")\n";
    boost::trim_right(s); cout << "(" << s << ")\n";
    boost::trim_left(s);  cout << "(" << s << ")\n";
}

Kết quả

(  Hello World  )
(  Hello World)
(Hello World)

C++23: sẽ có std::trim trong <string>.