C++ string 的 trim 函数

参考:

http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring

http://www.cppblog.com/cc/archive/2007/08/09/29667.html


代码如下:

#include <cctype>
#include <iostream>
#include <algorithm>

using namespace std;

inline string& ltrim(string &str) {
    string::iterator p = find_if(str.begin(), str.end(), not1(ptr_fun<int, int>(isspace)));
    str.erase(str.begin(), p);
    return str;
}

inline string& rtrim(string &str) {
    string::reverse_iterator p = find_if(str.rbegin(), str.rend(), not1(ptr_fun<int , int>(isspace)));
    str.erase(p.base(), str.end());
    return str;
}

inline string& trim(string &str) {
    ltrim(rtrim(str));
    return str;
}

int main(){
        string str = "\t\r\n ACB%&*KU234 \r\n";
        string str1 = str;
        string str2 = str;

        cout << "str: ~" << str << "~" << endl << endl;

        cout << "ltrim(str): ~" << ltrim(str1) << "~" << endl;
        cout << "rtrim(ltrim(str)): ~" << rtrim(str1) << "~" << endl << endl;

        cout << "rtrim(str): ~" << rtrim(str2) << "~" << endl;
        cout << "ltrim(rtrim(str)): ~" << ltrim(str2) << "~" << endl << endl;

        cout << "trim(str): ~" << trim(str) << "~" << endl;

        return 0;
}


运行结果:

str: ~
 ACB%&*KU234
~

ltrim(str): ~ACB%&*KU234
~
rtrim(ltrim(str)): ~ACB%&*KU234~

rtrim(str): ~
 ACB%&*KU234~
ltrim(rtrim(str)): ~ACB%&*KU234~

trim(str): ~ACB%&*KU234~

注意:

代码第8行、第14行的 ptr_fun<int, int>(isspace),如果写成 ptr_fun(isspace),编译时会报错:no matching function for call to ‘ptr_fun(<unresolved overloaded function type>)’


  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值