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 请按任意键继续. . .

    虽然加上命名空间限制,每个函数看起来都是那么长,但是用起来实际上还是非常简单的。

你可能感兴趣的:(算法)