使用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;
}

猜你喜欢

转载自blog.csdn.net/ancktion/article/details/81170355
今日推荐