boost trim

boost 字符串算法解密 修剪(trim.hpp)

trim 算法库中是用于修剪字符串的:



trim_left_copy_if()

trim_left_if()

trim_left_copy()

trim_left()

trim_right_copy_if()

trim_right_if()

trim_right_copy()

trim_right()

trim_copy_if()

trim_if()

trim_copy()

trim()

第一组

绿色

表示修剪字符串左端的空格(含 _if 的代表断言为真的字符)。



第二组

黄色

的表示修剪字符串右端的空格 (含_if 的代表断言为真的字符)。



第三组

紫色

的表示删除(修剪)两端。 (_if 含义同上)


一个简单的例子:

#pragma warning( disable : 4819 )

#include <iostream>
#include <algorithm>
#include <string>
#include <boost/algorithm/string.hpp>

using namespace std;

// 输出一个\才好看到字符串结尾的地方
#define PrintStr( str ) cout<< #str <<"="<< str <<"\\"<< endl

int main()
{
string str( " Hello World! " );
PrintStr( str );

string str1 = boost::trim_left_copy( str );
PrintStr( str );
PrintStr( str1 );

str1 = str;
PrintStr( str1 );
boost::trim_left( str1 );
PrintStr( str1 );

boost::trim_left_if( str1,boost::algorithm::is_upper() );
PrintStr( str1 );
str1 = str;
boost::trim_left_if( str1,boost::algorithm::is_upper() );
PrintStr( str1 );

str1 = boost::trim_copy( str );
PrintStr( str );
PrintStr( str1 );

boost::trim( str );
boost::trim_if( str, boost::algorithm::is_lower() );
PrintStr( str );
boost::trim_if( str, boost::algorithm::is_alpha() );
PrintStr( str );

return 0;
}
上面所有的

_copy

版本的函数都是基于这种模板的:



template<typename SequenceT, typename PredicateT>

SequenceT trim_left_copy_if(const SequenceT & Input, PredicateT IsSpace);

这种重载能够为 trim 提供强安全保证,下面还有一种重载,这在 trim 算法集中只有

_copy_if

版 本才有:



template<typename OutputIteratorT, typename RangeT, typename PredicateT>

OutputIteratorT trim_left_copy_if(OutputIteratorT Output, const RangeT & Input,

PredicateT IsSpace);

下面是这样的一个例子:

int main()
{
string str( " Hello World! " );
PrintStr( str );
string ss;
back_insert_iterator<string> it =
boost::algorithm::trim_left_copy_if( back_insert_iterator<string>(ss) ,
boost::make_iterator_range( str ),boost::algorithm::is_space() );
PrintStr( str );
PrintStr( ss );
*it = 'H';
PrintStr( ss );

ss.assign( str.begin(),str.end() );

PrintStr( ss );
string::iterator pos =
boost::algorithm::trim_copy_if( ss.begin(), boost::make_iterator_range( str ),
boost::algorithm::is_space() );
PrintStr( ss );

cout<< *pos << endl;

cout<< distance( ss.begin(),pos )<< endl;

return 0;
}
输出: str= Hello World! \ str= Hello World! \ ss=Hello World! \ ss=Hello World! H\ ss= Hello World! \ ss=Hello World!! \ H 0 请按任意键继续. . .

虽然加上命名空间限制,每个函数看起来都是那么长,但是用起来实际上还是非常简单的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值