ที่นี่เราจะดูวิธีการตัดแต่งสตริงใน C ++ สตริงการตัดแต่งหมายถึงการลบช่องว่างออกจากส่วนซ้ายและขวาของสตริง
ในการตัดแต่งสตริง C++ เราจะใช้ไลบรารีสตริงบูสต์ ในไลบรารีนั้น มีสองวิธีที่แตกต่างกันเรียกว่า trim_left() และ trim_right() หากต้องการตัดแต่งสายให้สมบูรณ์ เราสามารถใช้ทั้งสองอย่างได้
ตัวอย่าง
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
main(){
string myStr = " This is a string ";
cout << "The string is: (" << myStr << ")" << endl;
//trim the string
boost::trim_right(myStr);
cout << "The string is: (" << myStr << ")" << endl;
boost::trim_left(myStr);
cout << "The string is: (" << myStr << ")" << endl;
} ผลลัพธ์
$ g++ test.cpp $ ./a.out The string is: ( This is a string ) The string is: ( This is a string) The string is: (This is a string) $