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