为STL添加string::trim()
2007-06-26 16:53
232 查看
我对于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);
}
下面介绍个不同于正常人的方法. 虽然代码方面看上去不算很简洁, 但是效率的确不一般, 关键就在于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());
}
使用就更加简单了!
#include <string>
void main ()
{
string str1 = " sdfghj ";
trim1 (str1);
trim2 (str2);
}
下面这个方法十分简洁, 想必大家也看得明白, 不过由于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);
}
下面介绍个不同于正常人的方法. 虽然代码方面看上去不算很简洁, 但是效率的确不一般, 关键就在于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());
}
使用就更加简单了!
#include <string>
void main ()
{
string str1 = " sdfghj ";
trim1 (str1);
trim2 (str2);
}
相关文章推荐
- 为STL添加string::trim()
- C++中STL对string进行trim,split,replace操作
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- [javascript]String添加trim和reverse方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- STL 中的 std::string大小写转换 lowercase、uppercase、Trim、replace、split
- 給js的String添加trim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- JS中String添加trim()方法
- STL实现string的trim
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- JavaScript--在Javascript中为String对象添加trim,ltrim,rtrim方法
- 給js的String添加trim方法
- 在Javascript中为String对象添加trim,ltrim,rtrim方法
- JavaScript中为String对象添加 trim / ltrim / rtrim 方法