现在的位置: 首页 > 综合 > 正文

去掉空格

2013年09月10日 ⁄ 综合 ⁄ 共 1903字 ⁄ 字号 评论关闭
00001: /************************************************************************
00002: helper
00003: ************************************************************************/
00004: template<bool extendSpaceChar>
00005: struct SpaceCharUmpire {
00006: template<typename T>
00007: static inline bool execute(const T & t) {
00008: return 32==t || 9==t;
00009: }
00010: };
00011:
00012: template<>
00013: struct SpaceCharUmpire<true> {
00014: template<typename T>
00015: static inline bool execute(const T & t) {
00016: return t>0 && t<=32;
00017: }
00018: };
00019:
00020: /************************************************************************
00021: Trim space
00022: ************************************************************************/
00023: template<typename C=std::basic_string<char>, bool extendSpaceChar=false>
00024: struct Trim {
00025:
00026: //Trim Left
00027: static C & left(C & c) {
00028: for (typename C::iterator it=c.begin(); c.end()!=it; ++it) {
00029: if (!SpaceCharUmpire<extendSpaceChar>::execute(*it)) {
00030: c.erase(c.begin(), it);
00031: break;
00032: }
00033: }
00034: return c;
00035: }
00036:
00037: //Trim Right
00038: static C & right(C & c) {
00039: for (typename C::reverse_iterator it=c.rbegin(); c.rend()!=it; ++it) {
00040: if (!SpaceCharUmpire<extendSpaceChar>::execute(*it)) {
00041: c.erase(it.base(), c.end());
00042: break;
00043: }
00044: }
00045: return c;
00046: }
00047:
00048: //Trim All
00049: static C & all(C & c) { return right(left(c)); }
00050: };

2006.11.22.更新:原来的代码有一个BUG(第26行至46行),现更正如下:

00001:     //Trim Left
00002: static C & left(C & c) {
00003: for (typename C::iterator it=c.begin(); c.end()!=it; ++it) {
00004: if (!SpaceCharUmpire<extendSpaceChar>::execute(*it)) {
00005: c.erase(c.begin(), it);
00006: return c;
00007: }
00008: }
00009: c.clear();
00010: return c;
00011: }
00012:
00013: //Trim Right
00014: static C & right(C & c) {
00015: for (typename C::reverse_iterator it=c.rbegin(); c.rend()!=it; ++it) {
00016: if (!SpaceCharUmpire<extendSpaceChar>::execute(*it)) {
00017: c.erase(it.base(), c.end());
00018: return c;
00019: }
00020: }
00021: c.clear();
00022: return c;
00023: }
【上篇】
【下篇】

抱歉!评论已关闭.