C++ string 的 trim 函数

来源:互联网 发布:50岁知天命是什么年 编辑:程序博客网 时间:2024/05/18 19:18

参考:

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>)’


原创粉丝点击