我对于STL中未提供string::trim()接口表示不满已经有很久了! 对比Borland的产品, 发现Borland的接口定义相当精细和精准. 在此, 提供两种方法, 以实现string::trim(). (你别告诉我你连trim()是什么都不知道吧!!)
下面这个方法十分简洁, 想必大家也看得明白, 不过由于substr()使用了copy的方式, 致使效率方面下降许多(因为存在内容的再分配问题). 这种方式, 只要是个正常人都会第一时间想到它.
// simple way in STL
void trim1(string& str)
{
string::size_type pos1 = str.find_first_not_of(' ');
string::size_type pos2 = str.find_last_not_of(' ');
str = str.substr(pos1 == string::npos ? 0 : pos1,
pos2 == string::npos ? str.length() - 1 : pos2 - pos1 + 1);
}
void trim1(string& str)
{
string::size_type pos1 = str.find_first_not_of(' ');
string::size_type pos2 = str.find_last_not_of(' ');
str = str.substr(pos1 == string::npos ? 0 : pos1,
pos2 == string::npos ? str.length() - 1 : pos2 - pos1 + 1);
}
下面介绍个不同于正常人的方法. 虽然代码方面看上去不算很简洁, 但是效率的确不一般, 关键就在于erase().
// effecient way in STL
void trim2(string& str)
{
string::size_type pos = str.find_last_not_of(' ');
if(pos != string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
void trim2(string& str)
{
string::size_type pos = str.find_last_not_of(' ');
if(pos != string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
使用就更加简单了!
#include <string>
void main ()
{
string str1 = " sdfghj ";
trim1 (str1);
trim2 (str2);
}
}