在 C++ 中修剪 std::string 的最佳方法是什麼?
我們將在這裡學習如何在 C++ 中修剪字串。修剪字串是指去除字串左右兩邊的空白符。
要修剪 C++ 字串,我們將使用 boost 字串庫。在這個庫中,有兩個不同的方法,分別是 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) $
廣告