在 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)
$

更新于:30-Jul-2019

9K+ 浏览

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.