当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ boost::trim用法及代码示例


此函数包含在“boost/algorithm/string” 库中。 Boost 字符串算法库提供了 STL 中缺少的 string-related 算法的通用实现。 trim 函数用于从字符串中删除所有前导或尾随空格。输入序列已就地修改。

  • trim_left():从字符串中删除所有前导空格。
  • trim_right():从字符串中删除所有尾随空格。
  • trim():从字符串中删除所有前导和尾随空格。

用法:

Template:
trim(Input, Loc);

参数:
Input:输入序列
Loc:用于‘space’ 分类的语言环境

返回:修改后的输入序列没有前导或尾随空格。

例子:

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 <boost/algorithm/string.hpp>
#include <iostream>
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)


相关用法


注:本文由纯净天空筛选整理自newcybergypsy大神的英文原创作品 boost::trim in C++ library。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。