zoukankan      html  css  js  c++  java
  • 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   }

      

  • 相关阅读:
    Java集合类的操作笔记
    Java一维数组转换二叉树结构
    Python学习记录(一)
    Android测试读写sd卡文件与写sd卡文件耗时
    如何高效地分析Android_log中的问题?——查看Android源码
    Java替换字符串中的占位符
    Android 编译错误——布局 Error parsing XML: not well-formed (invalid token)
    Android Studio工程引用第三方so文件
    设计模式——设计模式之禅的阅读笔记
    Android Studio的快捷键
  • 原文地址:https://www.cnblogs.com/kidycharon/p/10042377.html
Copyright © 2011-2022 走看看