Effective STL 35 Case-insensitive string comparisons via mismatch or lexicographical_compare.

// case-insensitively compare chars c1 and c2
int ciCharCompare(char c1, char c2) {

    // tolower's parameter and return value is of type int, but unless that 
    // int is EOF, its value must be representable as an unsigned char
    int lc1 = tolower(stastic_cast<unsigned char>(c1));
    int lc2 = tolower(stastic_cast<unsigned char>(c2));

    if (lc1 < lc2) return -1;
    if (lc1 > lc1) return 1;
    return 0;
}

mismatch
It returns a pair of iterators indicating the locations in the ranges where corresponding characters first fail to match.

int ciStringComparelmpl(const string& s1, const string& s2);

// when we call mismatch, we have to make sure the shorter string is the
// first range passed;
int cisStringCompare(const sring& s1, const string& s2) {
    if (s1.size() <= s2.size()) return ciStringComparelmpl(s1, s2);
    else return -ciStringComparelmpl(s2, s1);
}

int ciStringComparelmp(const string& s1, const string& s2) {
    typedef pair<string::const_iterator, string::const_iterator> PSCI;
    PSCI p = mismatch(s1.begin(), s1.end(), s2.begin(), 
                        not2(ptr_func(ciCharCompare)));

    if(p.first == s1.end()) {
        if (p.second == s2.end()) return 0;
        else return -1;
    }

    return ciCharCompare(*p.first, *p.second);
}

lexicographical_compare is a generalized version of strcmp. it works with ranges of values of any type. Based on the results of calls to ciCharLess. if ciCharLess is true, so does lexicographical.

bool ciCharLess(char c1, char c2) {
    return 
        tolower(static_cast<unsigned char>(c1)) < 
        tolower(ststic_cast<unsigned char>(c2));
}

bool ciStringCompare(const string& s1, const string& s2) {
    return lexicographical_compare(s1.begin(), s1.end(), 
                                s2.begin(), s2.end(), isCharLess);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值