1. 程式人生 > >Effective_STL 學習筆記(三十五) 通過 mismatch 和 lexicographical 比較實現簡單的忽略大小寫字串比較

Effective_STL 學習筆記(三十五) 通過 mismatch 和 lexicographical 比較實現簡單的忽略大小寫字串比較

 

怎麼用 STL 進行忽略大小寫的字串的比較?

 

首先實現兩個字元忽略大小寫的比較:

 1   int ciCharCompare( char c1, char c2 )      // 忽略大小寫比較字元
 2   {
 3     int Ic1 = tolower( static_cast<unsigned char> (c1) );  // 都轉換成小寫
 4     int Ic2 = tolower( static_cast<unsigned char> (c2) );  // 標頭檔案<cctype>
 5     if
( Ic1 < Ic2 ) 6       return -1; 7     if( Ic1 > Ic2 ) 8       return 1; 9     return 0; 10   }

基於 mismatch 演算法,確定兩個區間中第一個對應的不相同的值的位置

 1   int ciStringCompare( const string & s1, const string & s2 )
 2   {
 3     if( s1.size() <= s2.size() )
 4       return ciStringCompareImpl( s1, s2 );
5     else 6       return -ciStringCompareImpl( s2, s1 ); 7   } 8   int ciStringCompareImpl( const string & s1, const string & s2 ) 9   { 10     typedef pair< string::const_iterator, string::const_iterator > PSCI; 11     PSCI p = mismatch( s1.begin(), s1.end(), s2.begin(), not2( ptr_fun( ciCharCompare ) ) );
12     if( p.first == s1.end() ) 13     { 14       if( p.second == s2.end() ) 15         return 0; 16       else 17         return -1; 18     } 19     return ciCharCompare( *p.first, *p.second ); 20   }

 

第二種方法 ciStringCompare 是產生一個合適的 STL 判斷式:可以在關聯容器中用作比較函式的函式,應用STL中名字第二長的演算法 —— lexicographical_compare:

1   bool ciCharLess( char c1, char c2 )
2   {
3     tolower( static_cast< unsigned char >(c1) < tower( static_cast< unsigned char >(c2) ) );
4   }
5   bool ciStringCompare( const string & s1, const string & s2 ) 6   { 7     return lexicographical_compare( s1.begin(), s1.end(), s2.begin(), s2.end(), ciCharLess ); 8   }

 

一個完全不用 STL 實現一個忽略大小寫字串比較最簡單的方式

1   int ciStringCompare( const string & s1, const string & s2 )
2   {
3     return stricmp( s1.c_str(), s2.c_str() );
4   }