C++的string前后去空格函数Trim

来源:互联网 发布:淘宝优惠券分享兼职 编辑:程序博客网 时间:2024/04/26 23:55

    String去前后空格函数Trim,仿照Cstring的Trim函数

#include "stdafx.h"#include<iostream> using namespace std;string trim(const string& str){    string::size_type pos = str.find_first_not_of(' ');    if (pos == string::npos)    {        return str;    }    string::size_type pos2 = str.find_last_not_of(' ');    if (pos2 != string::npos)    {        return str.substr(pos, pos2 - pos + 1);    }    return str.substr(pos);}int _tmain(int argc, _TCHAR* argv[]){    std::string str = " abc def    ";    std::string strTrim = trim(str);    cout << "Begin#" << strTrim.c_str() << "#End" <<endl;    return 0;}

其中Begin#和#end表现字符串的前后空格数。可以去除开头或者结尾的多个或一个空格。

运行结果:

    Begin#abc def#End

0 0
原创粉丝点击