天天看點

使用std實作string的TrimLeft與TrimRight功能

       使用過MFC的人都知道,MFC的字元串CString有些函數比較好用的,如: TrimLeft(), TrimRight()為CString所包含有的子函數,可以去掉左右空格符,但std::string卻沒有。

        以下我們使用std的标準函數來實作此功能:

#include <iostream>

#include <algorithm>

#include <string>

using namespace std;

template<typename _Tp>

inline bool is_not_space (_Tp a) {

  return !std::isspace(a);

}

void trim_left(string& pstr)

{

    string l_strtemp;

    std::string::iterator pfind = std::find_if(pstr.begin(),pstr.end(),is_not_space<std::string::value_type>);

    if(pfind!=pstr.end())

    {

        l_strtemp.assign(pfind,pstr.end());

        pstr = l_strtemp;

    }

}

void trim_right(string& pstr)

{

    string l_strtemp;

    std::string::reverse_iterator pfind = std::find_if(pstr.rbegin(),pstr.rend(),is_not_space<std::string::value_type>);

    if(pfind!=pstr.rend())

    {

        std::string::iterator pend(pfind.base());

        l_strtemp.assign(pstr.begin(),pend);

        pstr = l_strtemp;

    }

}

int main()

{

    std::string l_str(" \n test \n  ");

    trim_left(l_str);

    cout<<" test string:"<<l_str<<"#"<<endl;

    trim_right(l_str);

    cout<<" test string:"<<l_str<<"#"<<endl;

    return 0;

}