boost::trim 在 C++ 库中
该函数包含在“boost/algorithm/ 字符串”库中。 Boost 字符串算法库提供了 STL 中缺少的字符串相关算法的通用实现。修剪函数用于从字符串删除所有前导或尾随空格。输入序列就地修改。
- trim_left():从字符串删除所有前导空格。
- trim_right():从字符串删除所有尾随空格。
- trim():从字符串删除所有前导和尾随空格。
句法:
Template:
trim(Input, Loc);
Parameters:
Input: An input sequence
Loc: A locale used for ‘space’ classification
Returns: The modified input sequence without leading or trailing white spaces.
例子:
Input: ” geeks_for_geeks ”
Output: Applied left trim: “geeks_for_geeks ”
Applied right trim: ” geeks_for_geeks”
Applied trim: “geeks_for_geeks”
Explanation:
The trim_left() function removes all the leading white spaces.
The trim_right() function removes all the trailing white spaces.
The trim() function removes all the leading and trailing white spaces.
下面是使用函数boost::trim()从字符串删除空格的实现:
C++
// C++ program to remove white spaces
// from string using the function
// boost::trim function
#include
#include
using namespace boost::algorithm;
using namespace std;
// Driver Code
int main()
{
// Given Input
string s1 = " geeks_for_geeks ";
string s2 = " geeks_for_geeks ";
string s3 = " geeks_for_geeks ";
// Apply Left Trim on string, s1
cout << "The original string is: \""
<< s1 << "\" \n";
trim_left(s1);
cout << "Applied left trim: \""
<< s1 << "\" \n\n";
// Apply Right Trim on string, s2
cout << "The original string is: \""
<< s2 << "\" \n";
trim_right(s2);
cout << "Applied right trim: \""
<< s2 << "\" \n\n";
// Apply Trim on string, s3
cout << "The original string is: \""
<< s3 << "\" \n";
trim(s3);
cout << "Applied trim: \"" << s3
<< "\" \n";
return 0;
}
The original string is: " geeks_for_geeks "
Applied left trim: "geeks_for_geeks "
The original string is: " geeks_for_geeks "
Applied right trim: " geeks_for_geeks"
The original string is: " geeks_for_geeks "
Applied trim: "geeks_for_geeks"
时间复杂度: O(N)
辅助空间: O(1)